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 |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access