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.

This demonstrates the use of escape sequences and how to reference characters by their hexadecimal codes.

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, Python, Ruby
\a\e\f\n\r\t\x0B
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 by 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

Regex flavors

\a

bell

0x07

.NET, Java, PCRE, Perl, Python, Ruby

\e

escape

0x1B

.NET, Java, PCRE, Perl, Ruby

\f

form feed

0x0C

.NET, Java, JavaScript, PCRE, Perl, Python, Ruby

\n

line feed (newline)

0x0A

.NET, Java, JavaScript, PCRE, Perl, Python, Ruby

\r

carriage return

0x0D

.NET, Java, JavaScript, PCRE, Perl, Python, Ruby

\t

horizontal tab

0x09

.NET, Java, JavaScript, PCRE, Perl, Python, Ruby

\v

vertical tab

0x0B

.NET, Java, JavaScript, Python, Ruby

In Perl 5.10 and later, ...

Get Regular Expressions Cookbook, 2nd 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.