Analysis of the use of regular expressions in Ruby, analysis of ruby Regular Expressions
If you only need to search for the text of a string, do not use a regular expression: string ['text']
You can use string [/RE/] to query a simple structure.
match = string[/regexp/] # get content of matched regexp first_group = string[/text(grp)/, 1] # get content of captured group string[/text (grp)/, 1] = 'replace' # string => 'text replace'
When you do not need to group results, use non-group groups.
/(first|second)/ # bad /(?:first|second)/ # good
Do not use Perl legacy variables to represent matched regular groups (such as $1, $2, etc.). Use Regexp. last_match [n] as an alternative.
/(regexp)/ =~ string ... # bad process $1 # good process Regexp.last_match[1]
It is difficult to understand what they mean by using digital naming groups. Naming groups to replace.
# bad /(regexp)/ =~ string ... process Regexp.last_match[1] # good /(?<meaningful_var>regexp)/ =~ string ... process meaningful_var
Character classes have the following special keywords worth noting: ^,-, \,]. Therefore, do not escape. Or brackets in.
Note: ^ and $ match the beginning and end of A line, instead of the end of A string. If you want to match the entire string, use \ A and \ Z.
string = "some injection\nusername" string[/^username$/] # matches string[/\Ausername\Z/] # don't match
The x modifier is used for complex regular expressions. It can improve readability and add useful comments. Note that the white space characters are ignored.
regexp = %r{ start # some text \s # white space char (group) # first group (?:alt1|alt2) # some alternation end }x
Sub/gsub also supports hash and code block syntax, which can be used for replacement operations in complex situations.