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

Get Learning Rails: Live Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.