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 |
---|---|
| Form feed character |
| Newline character |
| Carriage return character |
| 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.