Sometimes you want to be able to search for strings without regard
to case, and you don’t want to put a lot of effort into creating an
expression that covers every option. Other times you want to search
against a string that contains many lines of text, and you don’t want
the expression to stop at the first line. For these situations, where
the underlying rules change, Ruby supports modifiers, which you can put
at the end of the expression or specify through the Regexp
object. A complete list of modifiers is
shown in Table C-3.
Table C-3. Regular expression modifier options
Modifier character | Effect |
---|---|
| Ignore case completely. |
| Multiline matching—look past the first newline, and
allow |
| Use extended syntax, allowing whitespace and comments in expressions. (Probably not the first thing you want to try!) |
| Only interpolate |
| Treat the content of the regular expression as Unicode. (By default, it is treated as the same as the content it is tested against.) |
| Treat the content of the regular expression as EUC,
SJIS, and ASCII, respectively, like |
Of these, i
and m
are the only ones you’re likely to use at
the beginning. To use them in a regular expression literal, just add
them after the closing :
sentence = "I think Ruby is the best Ruby-like programming language." sentence =~ /ruby/i # => 8 - "ruby" first appears at character 8.
If you want to use multiple options, you can. /ruby/iu
specifies case-insensitive Unicode matching, for instance.