Modifiers

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

i

Ignore case completely.

m

Multiline matching—look past the first newline, and allow . and to match newline characters.

x

Use extended syntax, allowing whitespace and comments in expressions. (Probably not the first thing you want to try!)

o

Only interpolate #{} expressions the first time the regular expression is evaluated. (Again, unlikely when starting out.)

u

Treat the content of the regular expression as Unicode. (By default, it is treated as the same as the content it is tested against.)

e, s, n

Treat the content of the regular expression as EUC, SJIS, and ASCII, respectively, like u does for Unicode.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset