O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Escaping

Of course, even in simple strings there can be a large problem: lots of characters you’ll want to test for are used by regular expression engines with a different meaning. The square braces around [0-9] are helpful for specifying that it’s a set starting with zero and going to nine, but what if you’re actually searching for square braces?

Fortunately, you can “escape” any character that regular expressions use for something else by putting a backslash in front of it. An expression that looks for left square brackets would look like \[. If you need to include a backslash, just put a second backslash in front of it, as in \\.

Some characters, particularly whitespace characters, are also just difficult to represent in a string without creating strange formatting. Table C-2 shows how to escape them for convenient matching.

Table C-2. Escapes for whitespace characters

Escape sequence

Meaning

\f

Form feed character

\n

Newline character

\r

Carriage return character

\t

Tab character

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required