Regular Expressions

  • Avoid using $1-9 as it can be hard to track
    what they contain. Named groups can be used instead.
    [link]

    1. # bad
    2. /(regexp)/ =~ string
    3. ...
    4. process $1
    5. # good
    6. /(?<meaningful_var>regexp)/ =~ string
    7. ...
    8. process meaningful_var
  • 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.[link]

    1. string = "some injection\nusername"
    2. string[/^username$/] # matches
    3. string[/\Ausername\z/] # don't match
  • Use x modifier for complex regexps. This makes
    them more readable and you can add some useful comments. Just be careful as
    spaces are ignored.[link]

    1. regexp = %r{
    2. start # some text
    3. \s # white space char
    4. (group) # first group
    5. (?:alt1|alt2) # some alternation
    6. end
    7. }x