Escaping Regular Expressions

Several TrafficScript functions take regular expressions as arguments. TrafficScript uses the PCRE regular expression library.

Regular expressions might contain a number of special characters:

. matches any single character.

? indicates that the previous expression is optional.

* matches any number of the previous expression.

^ matches the beginning of a string.

$ matches the end of a string.

If you want to match a literal period (.), or other special character in your regular expression, escape it with a backslash (\) character.

Like many other scripting languages, double-quoted TrafficScript strings use “\” as an escape character, so to place a regular expression like “^192\.168\.” into a TrafficScript double-quoted string, you must double-escape the “\” character:

# Sets the regex string as ^192\.168\.

# The two examples below have the same effect

$regex = "^192\\.168\\.";

$regex = '^192\.168\.';

if ( string.regexMatch( $ip, $regex ) ) {

  # IP is on 192.168.* network

}

Note that it’s not often necessary to use regular expressions in TrafficScript for the following reasons:

To search strings, you can use string.IPMaskMatch(), string.Contains(), string.startsWith() and string.endsWith().

To search and replace within strings, you can use string.replace() and string.replaceAll().