text
stringlengths
0
444
m = /(?<foo>FOO)(?<bar>BAR)/.match('FOOBAR')
p m[:foo] # => "FOO"
p m[:bar] # => "BAR"
# good - `(?:BAR)` is non-capturing grouping.
m = /(?<foo>FOO)(?:BAR)/.match('FOOBAR')
p m[:foo] # => "FOO"
# good - Both captures are accessible with numbers.
m = /(FOO)(BAR)/.match('FOOBAR')
p m[1] # => "FOO"
p m[2] # => "BAR"
----
=== Refer named regexp captures by name [[refer-named-regexp-captures-by-name]]
Prefer using names to refer named regexp captures instead of numbers.
[source,ruby]
----
# bad
m = /(?<foo>FOO)(?<bar>BAR)/.match('FOOBAR')
p m[1] # => "FOO"
p m[2] # => "BAR"
# good
m = /(?<foo>FOO)(?<bar>BAR)/.match('FOOBAR')
p m[:foo] # => "FOO"
p m[:bar] # => "BAR"
----
=== Avoid Perl-style Last Regular Expression Group Matchers [[no-perl-regexp-last-matchers]]
Don't use the cryptic Perl-legacy variables denoting last regexp group matches (`$1`, `$2`, etc).
Use `Regexp.last_match(n)` instead.
[source,ruby]
----
/(regexp)/ =~ string
...
# bad
process $1
# good
process Regexp.last_match(1)
----
=== Avoid Numbered Groups [[no-numbered-regexes]]
Avoid using numbered groups as it can be hard to track what they contain.
Named groups can be used instead.
[source,ruby]
----
# bad
/(regexp)/ =~ string
# some code
process Regexp.last_match(1)
# good
/(?<meaningful_var>regexp)/ =~ string
# some code
process meaningful_var
----
=== Limit Escapes [[limit-escapes]]
Character classes have only a few special characters you should care about: `^`, `-`, `\`, `]`, so don't escape `.` or brackets in `[]`.
=== Caret and Dollar Regexp [[caret-and-dollar-regexp]]
Be careful with `^` and `$` as they match start/end of line, not string endings.
If you want to match the whole string use: `\A` and `\z` (not to be confused with `\Z` which is the equivalent of `/\n?\z/`).
[source,ruby]
----
string = "some injection\nusername"
string[/^username$/] # matches
string[/\Ausername\z/] # doesn't match
----
=== Multi-line Regular Expressions [[multi-line-regexes]]
Use `x` (free-spacing) modifier for multi-line regexps.
NOTE: That's known as https://www.regular-expressions.info/freespacing.html[free-spacing mode]. In this mode leading and trailing whitespace is ignored.
[source,ruby]
----
# bad
regex = /start\
\s\
(group)\
(?:alt1|alt2)\
end/
# good
regexp = /
start