Section 3.3. Escaping Special Characters

3.2. Compiling Regular Expressions

Regular expressions can be compiled using the class method Regexp.compile (which is really only a synonym for The first parameter is required and may be a string or a regex. (Note that if the parameter is a regex with options, the options will not carry over into the newly compiled regex.)

pat1 = Regexp.compile("^foo.*")  # /^foo.*/ pat2 = Regexp.compile(/bar$/i)   # /bar/ (i not propagated)

The second parameter, if present, is normally a bitwise OR of any of the following constants Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE. Additionally, any non-nil value will have the result of making the regex case-insensitive; we do not recommend this practice.

options = Regexp::MULTILINE || Regexp::IGNORECASE pat3 = Regexp.compile("^foo", options) pat4 = Regexp.compile(/bar/, Regexp::IGNORECASE)

The third parameter, if it is specified, is the language parameter, which enables multibyte character support. It can take any of four string values:

"N" or "n" means None "E" or "e" means EUC "S" or "s" means Shift-JIS "U" or "u" means UTF-8

Of course, regular expression literals may be specified without calling new or compile, simply by enclosing them in slash delimiters.

pat1 = /^foo.*/ pat2 = /bar$/i

For more information, see Chapter 4.

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: