If you just need to find the text of the string, do not use regular expressions: string[' text '
For simple structures, you can query directly using the string[/re/] approach.
Match = string[/regexp/] # Get content of matched regexp
first_group = string[/text (GRP)/, 1] # get content of Cap tured Group
String[/text (GRP)/, 1] = ' Replace ' # string => ' text replace '
When you don't need to group results, use groups that are not grouped.
/(First|second)/ # bad
/(?: First|second)/# Good
Do not use Perl legacy variables to represent matching regular groupings (such as $1,$2, etc.), using regexp.last_match[n] as an alternative.
/(RegExp)/=~ string
...
# bad
process
# good
process regexp.last_match[1]
It's hard to understand what they mean by avoiding the use of digital naming groups. Named groups to override.
# Bad
/(regexp)/=~ string
...
Process regexp.last_match[1]
# good
/(? <meaningful_var>regexp)/=~ string
...
Process Meaningful_var
The character class has the following special keywords to note: ^,-, \,], so, do not escape. or parentheses in the [].
Note that ^ and $, they match the beginning and end of the line, not the ending of a string, if you want to match the entire string, with \a and \z.
String = "Some Injection\nusername"
string[/^username$/] # matches
string[/\ausername\z/] # don ' t Match
For complex regular expressions, use an x modifier. You can improve readability and add useful annotations. Just be aware that whitespace characters are ignored.
RegExp =%r{
start # some text
\s # white space char
(group) # a
(?: alt1| ALT2) # Some alternation
end
}x
Sub/gsub also supports hashing and code block formal syntax, which can be used in complex case substitution operations.