2.2. Match Nonprintable Characters
Problem
Match a string of the following ASCII control characters: bell, escape, form feed, line feed, carriage return, horizontal tab, vertical tab. These characters have the hexadecimal ASCII codes 07, 1B, 0C, 0A, 0D, 09, 0B.
Solution
\a\e\f\n\r\t\v
| Regex options: None |
| Regex flavors: .NET, Java, PCRE, Python, Ruby |
\x07\x1B\f\n\r\t\v
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Python, Ruby |
\a\e\f\n\r\t\0x0B
| Regex options: None |
| Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
Discussion
Seven of the most commonly used ASCII control characters have dedicated escape sequences. These all consist of a backslash followed by a letter. This is the same syntax that is used for string literals in many programming languages. Table 2-1 shows the common nonprinting characters and how they are represented.
Table 2-1. Nonprinting characters
Representation | Meaning | Hexadecimal representation |
|---|---|---|
‹ | bell | 0x07 |
‹ | escape | 0x1B |
‹ | form feed | 0x0C |
‹ | line feed (newline) | 0x0A |
‹ | carriage return | 0x0D |
‹ | horizontal tab | 0x09 |
‹ | vertical tab | 0x0B |
Perl does not support \v, so
we have to use a different syntax for the vertical tab in Perl. The
ECMA-262 standard does not support ‹› and
‹\a›. Therefore, we use a different
syntax for the JavaScript examples in this book, even though many
browsers do support ‹\e\a›
and ‹\e›.
These control characters, as well as the alternative syntax shown in the following section, can be used equally inside and outside character classes in your regular ...
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