O'Reilly logo

Regular Expressions Cookbook by Steven Levithan, Jan Goyvaerts

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

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

\a

bell

0x07

\e

escape

0x1B

\f

form feed

0x0C

\n

line feed (newline)

0x0A

\r

carriage return

0x0D

\t

horizontal tab

0x09

\v

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 \a and \e. Therefore, we use a different syntax for the JavaScript examples in this book, even though many browsers do support \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 ...

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