XML technologies / Regular expressions / Features and dialects / Strings, character encodings, and modes / Strings as regular expressions

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

In most languages except Perl, awk and sed, the regex engine receives regexes as strings, often literals such as “^From:(.*)”. Strings have their own metacharacters, distinct from regex metacharacters, which often confuses beginners.

Each language, and sometimes each literal type, has its own rules. General principles are similar: sequences such as \t, \\ and \x2A become single characters when constructing strings. Regex backslashes therefore usually need doubling. For ˹\n˼, write “\\n”.

Omitting the extra backslash and writing only “\n” usually produces ˹NL˼, often equivalent to ˹\n˼. But in free-spacing mode with /x or equivalent, ˹NL˼ becomes an empty regex, while ˹\n˼ still matches newline. The table gives examples with \t and \x2A (2A is ASCII hex for ›*‹). The last columns show accidental single-backslash effects.

Table: string literal examples.

String literal

"[\t\x2A]"

"[\\t\\x2A]"

"\t\x2A"

"\\t\\x2A"

String value

›[TAB*]‹

›[\t\x2A]‹

›TAB*‹

›\t\x2A‹

Interpreted as regex

˹[TAB*]˼

˹[\t\x2A]˼

˹TAB*˼

˹\t\x2A˼

Matches

Tab or asterisk

Tab or asterisk

Any number of tabs

Tab then asterisk

In /x mode

Tab or asterisk

Tab or asterisk

Error

Tab then asterisk

Some languages differ greatly because ›\‹ is not special. VB.NET has only one string metacharacter: double quote. Always ask what the regex engine sees after the language parses the string.

 

Java strings

As introduced, Java literals use double quotes and backslash escapes such as ›\t‹ for tab, ›\n‹ for newline, and ›\\‹ for backslash. Unknown escapes are errors.

 

VB.NET strings

VB.NET uses double quotes, but backslash is ordinary. Its only escape is a doubled quote for one literal quote. For example, "Er sagte ""hallo""\." becomes ˹Er sagte "hallo".\˼.

C# strings

.NET languages share a regex engine but have different string rules. Visual Basic has one simple literal type; C# has two.

C# has ordinary double-quoted strings, except a literal quote is inserted with "" rather than \". Verbatim strings use @"...", without backslash processing, except a quote can be inserted with \" . Thus ˹\t\x2A˼ can be written “\\t\\x2A” or as the verbatim string @"\t\x2A" . Verbatim strings simplify most regexes.

 

PHP strings

In PHP, both string types differ from C#. Double quotes allow standard escapes such as ›\n‹ and interpolate variables, like Perl. Furthermore, {...} inserts the result of enclosed PHP code.

Double-quoted PHP regex strings therefore need many backslashes. Unlike Java and C#, unknown PHP escapes pass both characters unchanged. PHP recognizes \t as a string escape, requiring "\\t" for regex ˹\t˼, but "\w" yields ˹\w˼ because \w is an unknown string escape. This reduces backslashes but can confuse.

PHP single-quoted strings are simpler, like VB.NET or C# @"..." strings. However, \' inserts a single quote, and \\ before the closing quote lets the string end with a backslash. All other characters pass unchanged. Thus '\t\x2A' simply becomes ˹\t\x2A˼. Single quotes are normally preferred for PHP regexes.

PHP single-quoted strings are discussed later.

Python strings

In Python, single and double quotes are equivalent. Triple-quoted strings use '''...''' or """...""" and may span lines. All four types allow \n style escapes, with unknown backslashes retained like PHP rather than errors as in Java/C#.

Python also offers simpler raw strings, marked like C#'s @"..." notation with a leading ›r‹. Prefix any of its four string types with ›r‹ for raw: r"\t\x2A" produces ˹\t\x2A˼. These strings treat all backslashes literally, so r"Er sagte \"hallo\"\." produces ˹Er sagte \"hallo\"\.˼. Regexes generally handle this because Python treats ˹\"˼ and ˹"˼ alike. Alternatively, change delimiters: r'Er sagte "hallo"\.'

Tcl strings

Tcl has no true string literals. Command words may represent variables, strings, regexes, etc. Word parsing translates certain escapes such as \n and discards backslashes on unknown escapes. Double quotes are needed only for words containing whitespace.

Tcl also has raw-like strings, similar to Python's r'...' strings, but uses braces. Within r'...', everything except backslash-newline passes unchanged, so use {\t\x2A} for ˹\t\x2A˼.

Balanced braces may nest. Unmatched braces require backslash escaping, retained in the resulting string.

Perl regex literals

Perl examples have used regex literals, but strings work too. For example,

$str =~ m/(\w+)/;

can be written:

$regex = '(\w+)';
$str =~ $regex;

or:

$regex = "(\\w+)";
$str =~ $regex;

(Strings may, however, be much less efficient.)

Literals provide features outside the regex engine itself:

  • Variable interpolation replaces names with values.

  • Literal text through ˹\Q...\E˼.

  • The construct \N{Name} names characters by their official Unicode name. For example, ˹\N{INVERTED EXCLAMATION MARK}Hola!˼ matches ›¡Hola!‹.

Perl processes regex literals like special strings; ordinary double-quoted strings support these features too. Crucially, they are not regex-engine features. Users often assume ˹\Q...\E˼ belongs to the regex dialect. When loading patterns from files or arguments, knowing which language layer supplies a feature is essential.

Under Perl, see Regex operands and literals for more.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top