Working with String Patterns

Introduction

The general symbolic string patterns in the Wolfram Language allow you to perform powerful string manipulation efficiently. What follows discusses the details of string patterns, including usage and implementation notes. The emphasis is on issues not mentioned elsewhere in the help system.

At the heart of the Wolfram Language is a powerful language for describing patterns in general expressions. This language is used in function definitions, substitutions, and searches, with constructs like , , , and so on.
In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=
In[3]:=
Click for copyable input
Out[3]=
A Wolfram Language string pattern uses the same constructs to describe patterns in a text string. You can think of a string as a sequence of characters and apply the principles of general Wolfram Language patterns. In addition there are several useful string-specific pattern constructs.
In[4]:=
Click for copyable input
Out[4]=
In[5]:=
Click for copyable input
Out[5]=
In[6]:=
Click for copyable input
Out[6]=
Regular expressions can be used as an alternative way to specify string patterns. These tend to be more compact, but less readable.
In[7]:=
Click for copyable input
Out[7]=
In[8]:=
Click for copyable input
Out[8]=
In[9]:=
Click for copyable input
Out[9]=

Here is a list of several functions that recognize string patterns.

StringMatchQ["s",patt]test whether s matches patt
StringFreeQ["s",patt]test whether s is free of substrings matching patt
StringCases["s",patt]give a list of the substrings of s that match patt
StringCases["s",lhs->rhs]replace each case of lhs by rhs
StringPosition["s",patt]give a list of the positions of substrings that match patt
StringCount["s",patt]count how many substrings match patt
StringReplace["s",lhs->rhs]replace every substring that matches lhs
StringReplaceList["s",lhs->rhs]give a list of all ways of replacing lhs
StringSplit["s",patt]split s at every substring that matches patt
StringSplit["s",lhs->rhs]split at lhs, inserting rhs in its place

Functions that support string patterns.

General String Patterns

A general string pattern is formed from pattern objects similar to the general pattern objects in the Wolfram Language. To join several string pattern objects, use the StringExpression operator .
In[10]:=
Click for copyable input
Out[10]//FullForm=
StringExpression is closely related to StringJoin, except nonstrings are allowed and lists are not flattened. For pure strings, they are equivalent.
In[11]:=
Click for copyable input
Out[11]=

The list of objects that can appear in a string pattern closely matches the list for ordinary Wolfram Language patterns. In terms of string patterns, a string is considered a sequence of characters, that is, can be thought of as something like String[a,b,c], to which the ordinary pattern constructs apply.

The following objects can appear in a symbolic string pattern:

"string"a literal string of characters
_any single character
__any substring of one or more characters
___any substring of zero or more characters
x_,x__,x___substrings given the name x
x:patternpattern given the name x
pattern..pattern repeated one or more times
pattern...pattern repeated zero or more times
{patt1,patt2,} or patt1|patt2|a pattern matching at least one of the
patt/;conda pattern for which cond evaluates to True
pattern?testa pattern for which test yields True for each character
Whitespacea sequence of whitespace characters
NumberStringthe characters of a number
DatePattern[spec]the characters of a date
charobjan object representing a character class (see below)
RegularExpression["regexp"]substring matching a regular expression
StringExpression[]an arbitrary string expression

The following represent classes of characters:

{c1,c2,}any of the
Characters["c1c2"]any of the
CharacterRange["c1","c2"]any character in the range to
HexadecimalCharacterhexadecimal digit 09, af, AF
DigitCharacterdigit 09
LetterCharacterletter
WhitespaceCharacterspace, newline, tab, or other whitespace character
WordCharacterletter or digit
Except[p]any character except ones matching p

The following represent positions in strings:

StartOfStringstart of the whole string
EndOfStringend of the whole string
StartOfLinestart of a line
EndOfLineend of a line
WordBoundaryboundary between word characters and others
Except[WordBoundary]anywhere except a word boundary

The following determine which match will be used if there are several possibilities:

Shortest[p]the shortest consistent match for p
Longest[p]the longest consistent match for p (default)

Some nontrivial issues regarding these objects follow.

The , , and wildcards match any characters including newlines. To match any character except newline (analogous to the "." in regular expressions), use Except["\n"], Except["\n"].., and Except["\n"]....
In[12]:=
Click for copyable input
Out[12]=
In[13]:=
Click for copyable input
Out[13]=
In[14]:=
Click for copyable input
Out[14]=
A list of patterns, such as , is equivalent to a list of alternatives, such as . This is convenient in that functions like Characters and CharacterRange can be used to specify classes of characters.
In[15]:=
Click for copyable input
Out[15]=
When Condition () is used, the patterns involved are treated as strings as far as the rest of the Wolfram Language is concerned, so you need to use ToExpression in some cases.
In[16]:=
Click for copyable input
Out[16]=
Similar to ordinary Wolfram Language patterns, the function in PatternTest () is applied to each individual character.
In[17]:=
Click for copyable input
Out[17]=
The Whitespace construct is equivalent to WhitespaceCharacter...
In[18]:=
Click for copyable input
Out[18]=
You can insert a RegularExpression object into a general string pattern.
In[19]:=
Click for copyable input
Out[19]=
This inserts a lookbehind constraint (see "Regular Expressions") to ensure that you only pick words preceded by .
In[20]:=
Click for copyable input
Out[20]=
StringExpression objects can be nested.
In[21]:=
Click for copyable input
Out[21]=

The Except construct for string patterns takes a single argument that should represent a single character or a class of single characters.

This deletes all nonvowel characters from the string.
In[22]:=
Click for copyable input
Out[22]=
When trying to match patterns of variable length (such as and ), the longest possible match is tried first by default. To force the matcher to try the shortest match first, you can wrap the relevant part of the pattern in Shortest[ ].
In[23]:=
Click for copyable input
Out[23]=
In[24]:=
Click for copyable input
Out[24]=
If for some reason you need a longest match within the short match, you can use Longest.
In[25]:=
Click for copyable input
Out[25]=
In[26]:=
Click for copyable input
Out[26]=
You could alternatively rewrite this pattern without use of Longest.
In[27]:=
Click for copyable input
Out[27]=

Regular Expressions

The regular expression syntax follows the underlying Perl Compatible Regular Expressions (PCRE) library, which is close to the syntax of Perl. (See [1] for further information and documentation.) A regular expression in the Wolfram Language is denoted by the head RegularExpression.

The following basic elements can be used in regular expression strings:

cthe literal character c
.any character except newline
[c1c2]any of the characters
[c1-c2]any character in the range
[^c1c2]any character except the
p*p repeated zero or more times
p+p repeated one or more times
p?zero or one occurrence of p
p{m,n}p repeated between m and n times
p*?,p+?,p??the shortest consistent strings that match
p*+,p++,p?+possessive match
(p1p2)strings matching the sequence , ,
p1|p2strings matching or

The following represent classes of characters:

\\ddigit 09
\\Dnondigit
\\sspace, newline, tab, or other whitespace character
\\Snonwhitespace character
\\wword character (letter, digit, or )
\\Wnonword character
[[:class:]]characters in a named class
[^[:class:]]characters not in a named class

The following named classes can be used: alnum, alpha, ascii, blank, cntrl, digit, graph, lower, print, punct, space, upper, word, and xdigit.

The following represent positions in strings:

^the beginning of the string (or line)
$the end of the string (or line)
\\Athe beginning of the string
\\zthe end of the string
\\Zthe end of the string (allowing for a single newline character first)
\\bword boundary
\\Banywhere except a word boundary

The following set options for all regular expression elements that follow them:

(?i)treat uppercase and lowercase as equivalent (ignore case)
(?m)make and match start and end of lines (multiline mode)
(?s)allow to match newline
(?x)disregard all whitespace and treat everything between and as comments
(?-#c)unset options

The following are lookahead/lookbehind constructs:

(?=p)the following text must match p
(?!p)the following text cannot match p
(?<= p)the preceding text must match p
(?<!p)the preceding text cannot match p

Discussion of a few issues regarding regular expressions follows.

This looks for runs of word characters of length between 2 and 4.
In[28]:=
Click for copyable input
Out[28]=
With the possessive quantifier, as many characters as possible are grabbed by the matcher, and no characters are given up, even if the rest of the patterns require it.
In[29]:=
Click for copyable input
Out[29]=
In[30]:=
Click for copyable input
Out[30]=
In[31]:=
Click for copyable input
Out[31]=
corresponds to characters in a hexadecimal number.
In[32]:=
Click for copyable input
Out[32]=

The complete list of characters that need to be escaped in a regular expression consists of , , , , , , , , , , , , , and . For instance, to write a literal period, use and to write a literal backslash, use .

Inside a character class , the complete list of escaped characters is , , , , and .

By default, and match the beginning and end of the string, respectively. In multiline mode, these match the beginning/end of lines instead.
In[33]:=
Click for copyable input
Out[33]=
In[34]:=
Click for copyable input
Out[34]=
In multiline mode, and can be used to denote the beginning and end of the string.
In[35]:=
Click for copyable input
Out[35]=
The modifier allows you to add whitespace and comments to a regular expression for readability.
In[36]:=
Click for copyable input
Out[36]=
Named subpatterns are achieved by surrounding them with parentheses (subpatt); they then become numbered subpatterns. The number of a given subpattern counts the opening parenthesis, starting from the start of the pattern. You can refer to these subpatterns using \\n for the n^(th) pattern later in the pattern, or by in the right-hand side of a rule. refers to all of the matched pattern.
In[37]:=
Click for copyable input
Out[37]=
In[38]:=
Click for copyable input
Out[38]=
If you need a literal in this context (when the head of the left-hand side is RegularExpression), you can escape it by using backslashes (for example, ).
In[39]:=
Click for copyable input
Out[39]=
If you happen to need a single literal backslash followed by a literal under these circumstances, you need to be a bit tricky and split into two strings temporarily.
In[40]:=
Click for copyable input
Out[40]=
If you need to group a part of the pattern, but you do not want to count the group as a numbered subpattern, you can use the construct.
In[41]:=
Click for copyable input
Out[41]=

Lookahead and lookbehind patterns are used to ensure a pattern is matched without actually including that text as part of the match.

This picks out words following the string .
In[42]:=
Click for copyable input
Out[42]=
This tries to pick out all even numbers in the string, but it will find matches that include partial numbers.
In[43]:=
Click for copyable input
Out[43]=
Using lookbehind/lookahead, you can ensure that the characters before/after the match are not digits (note that the lookbehind test is superfluous in this particular case).
In[44]:=
Click for copyable input
Out[44]=

RegularExpression versus StringExpression

There is a close correspondence between the various pattern objects that can be used in general symbolic string patterns and in regular expressions. Here is a list of examples of patterns written as regular expressions and as symbolic string patterns.

regular expression
general string pattern
explanation
"abc""abc"the literal string
"."Except["\n"]any character except newline
"(?s)."_any character
"(?s).+"__one or more characters (greedy)
"(?s).+?"Shortest[__]one or more characters (nongreedy)
"(?s).*"___zero or more characters
".*"Except["\n"]...zero or more characters (except newlines)
"a?b""a"|""~~"b"zero or one followed by a (that is, or )
"[abef]"Characters["abef"]any of the characters , , , or
"[abef]+"Characters["abef"]..one or more of the characters , , , or
"[a-f]"CharacterRange["a","f"]any character in the range between and
"[^abef]"Except[Characters["abef"]]any character except the characters , , , or
"ab|efg""ab"|"efg"match the strings or
"(ab|ef)gh"or"(?:ab|ef)gh"("ab"|"ef")~~"gh" or followed by (that is, or )
"\\s"WhitespaceCharacterany whitespace character
"\\s+"Whitespaceone or more characters of whitespace
"(a|b)\\1"x:"a"|"b"~~x_this will match either or
"\\d"DigitCharacterany digit character
"\\D"Except[DigitCharacter]any nondigit character
"\\d+"DigitCharacter..one or more digit characters
"\\w"WordCharacter|"_"any digit, letter, or character
"[[:alpha:]]"LetterCharacterany letter character
"[^[:alpha:]]"Except[LetterCharacter]any nonletter character
"^abf"or"\\Aabc"StartOfString~~"abf"the string at the start of the string
"(?m)^abf"StartOfLine~~"abf"the string at the start of a line
"wxz$"or"wxz\\z""wxz"~~EndOfStringthe string at the end of the string
"wxz\\Z""wxz"~~"\n"|""~~EndOfStringthe string at the end of the string or before newline at the end of the string

Pattern objects that can be used in general string patterns, but not in regular expressions, include conditions () and pattern tests () that can access general Wolfram Language code during the match.

Some special constructs in regular expressions are not directly available in general string patterns. These include lookahead/lookbehinds and repeats of a given length. They can be embedded into a larger general string pattern by inserting a RegularExpression object.

String Manipulation Functions

The following discusses some particulars and subtleties in the various string manipulation functions (see the reference pages for more information on these functions).

StringMatchQ

StringMatchQ is used to check whether a whole string matches a certain pattern.
In[45]:=
Click for copyable input
Out[45]=
In[46]:=
Click for copyable input
Out[46]=

StringMatchQ is special in that it also allows the metacharacters and to be entered as wildcards (for backward compatibility reasons). is equivalent to Shortest[___] (RegularExpression["(?s).*?"]) and is equivalent to Except[CharacterRange["A","Z"]] (RegularExpression["[^A-Z]"]).

The following three patterns are therefore equivalent.
In[47]:=
Click for copyable input
Out[47]=
In[48]:=
Click for copyable input
Out[48]=
In[49]:=
Click for copyable input
Out[49]=

Note that technically the appearance of Shortest does not make a difference here, since we are only looking for a possible match.

If you need to access parts of the string matched by subpatterns in the pattern, use StringCases instead.

StringMatchQ has a SpellingCorrection option for finding matches allowing for a small number of discrepancies. This only works for patterns consisting of a single literal string.
In[50]:=
Click for copyable input
Out[50]=

StringFreeQ

StringFreeQ is used to check whether a string contains a substring matching the pattern. You cannot extract the matching substring; to do this you would use StringCases.
In[51]:=
Click for copyable input
Out[51]=
In[52]:=
Click for copyable input
Out[52]=

StringCases

StringCases is a general purpose function for finding occurrences of patterns in a string, picking out subpatterns, and processing the results.

Find substrings matching a pattern.
In[53]:=
Click for copyable input
Out[53]=
Pick apart the matching substring.
In[54]:=
Click for copyable input
Out[54]=
In[55]:=
Click for copyable input
Out[55]=
Restrict the number of matches.
In[56]:=
Click for copyable input
Out[56]=
You can use a list of rules.
In[57]:=
Click for copyable input
Out[57]=
You can also give a list of strings as the first argument for efficient processing of many strings (see "Tips and Tricks for Efficient Matching" for a discussion).
In[58]:=
Click for copyable input
Out[58]=
In[59]:=
Click for copyable input
Out[59]=

The Overlaps Option

The Overlaps option for StringCases, StringPosition, and StringCount deals with how the matcher proceeds after finding a match. It has three possible settings: False, True, or All. The default is False for StringCases and StringCount, while it is True for StringPosition.

With Overlaps->False, the matcher continues the match testing at the character following the last matched substring.
In[60]:=
Click for copyable input
Out[60]=
With Overlaps->True, the matcher continues at the character following the first character of the last matched substring (when a single pattern is involved).
In[61]:=
Click for copyable input
Out[61]=
With Overlaps->All, the matcher keeps starting at the same position until no more new matches are found.
In[62]:=
Click for copyable input
Out[62]=
If multiple patterns are given in a list, Overlaps->True will cause the matcher to start at the same position once for each of the patterns before proceeding to the next character.
In[63]:=
Click for copyable input
Out[63]=
In[64]:=
Click for copyable input
Out[64]=
Note that with Overlaps->True, there can thus be a difference between specifying a list of patterns and using the alternatives operator ().
In[65]:=
Click for copyable input
Out[65]=
In[66]:=
Click for copyable input
Out[66]=

StringPosition

StringPosition works much like StringCases, except the positions of the matching substrings are returned.
In[67]:=
Click for copyable input
Out[67]=
In[68]:=
Click for copyable input
Out[68]=
The Overlaps option is True by default (see the previous section for more details on this option).
In[69]:=
Click for copyable input
Out[69]=
Note that even empty strings can be matches.
In[70]:=
Click for copyable input
Out[70]=

StringCount

StringCount returns the number of matching substrings (which are found by StringPosition or StringCases). It is useful for cases with many matches where memory for storing all the substrings might be an issue.
In[71]:=
Click for copyable input
Out[71]=
In[72]:=
Click for copyable input
Out[72]=

Note that Overlaps->False is the default for StringCount.

StringReplace

StringReplace is used for substituting substrings matching the given patterns.
In[73]:=
Click for copyable input
Out[73]=
Named patterns can be used as strings on the right-hand side of the replacement rules. Note the use of RuleDelayed () to avoid premature evaluation.
In[74]:=
Click for copyable input
Out[74]=
When using regular expressions, it is convenient to remember that on the right-hand side refers to the whole matched substring.
In[75]:=
Click for copyable input
Out[75]=
You can limit the number of replacements made by specifying a third argument.
In[76]:=
Click for copyable input
Out[76]=
Note that the replacement does not have to be a string. If the result is not a string, a StringExpression is returned.
In[77]:=
Click for copyable input
Out[77]=
In[78]:=
Click for copyable input
Out[78]//FullForm=

There is limited support for using the old option in conjunction with general string patterns, but this option is deprecated and its use should be avoided.

StringReplaceList

StringReplaceList returns a list of strings where a single string replacement has been made in all possible ways.
In[79]:=
Click for copyable input
Out[79]=
If a list of strings is given as input, the output is a nested list of results.
In[80]:=
Click for copyable input
Out[80]=

StringSplit

StringSplit is useful for splitting a string into many strings at delimiters matching a pattern. By default, the splits happen at runs of whitespace.
In[81]:=
Click for copyable input
Out[81]=
For instance, to split a normal sentence into words, you need to also include punctuation in the delimiter.
In[82]:=
Click for copyable input
Out[82]=
By default, empty strings at the beginning and the end of the result are removed.
In[83]:=
Click for copyable input
Out[83]=
These can be included by specifying All as a third argument.
In[84]:=
Click for copyable input
Out[84]=
The third argument can also be a number giving the maximum number of strings to split into.
In[85]:=
Click for copyable input
Out[85]=
This splits a string into individual lines.
In[86]:=
Click for copyable input
Out[86]=
You can also split at patterns that match positions, such as StartOfLine. This keeps the newline characters in the result.
In[87]:=
Click for copyable input
Out[87]=
You can keep the delimiters, or parts of the delimiters, in the output by using a rule as the second argument.
In[88]:=
Click for copyable input
Out[88]=
In[89]:=
Click for copyable input
Out[89]=
In[90]:=
Click for copyable input
Out[90]=
In[91]:=
Click for copyable input
Out[91]=
You can give a list of patterns and rules as well; the delimiters matching the patterns will be left out of the result.
In[92]:=
Click for copyable input
Out[92]//InputForm=

For Perl Users

Overview

With the addition of general string patterns, the Wolfram Language can be a powerful alternative to languages like Perl and Python for many general, everyday programming tasks. For people familiar with Perl syntax, and the way Perl does string manipulation, the following rough guide shows how to get similar functionality in the Wolfram Language.

Here is an overview of the Wolfram Language functions involved in constructing Perl-like functions.

Perl construct
Wolfram Language function
explanation
m/ .../StringFreeQ or StringCasesmatch a string with a regular expression, possibly extracting subpatterns
s/ .../ .../StringReplacereplace substrings matching a regular expression
split(...)StringSplitsplit a string at delimiters matching a regular expression
tr/ .../ .../StringReplacereplace characters by other characters
/iIgnoreCase->True or "(?i)"case-insensitive modifier
/s"(?s)"force to match all characters (including newlines)
/x"(?x)"ignore whitespace and allow extended comments in regular expression
/m"(?m)"multiline mode ( and match start/end of lines)

Following are some common Perl constructs in more detail.

m/.../

The match operator tests whether a string contains a substring matching the . For simple matches of this sort in the Wolfram Language, use StringFreeQ.

Here is a Perl snippet for testing whether a string contains a somewhere after an .
Here is a Wolfram Language version of the same test.

If parts of the matched string need to be accessed later, using , , in Perl, the best Wolfram Language function to use is normally StringCases.

Here is Perl code for extracting an error message.
Here is a Wolfram Language version.
Here is Perl code for extracting several subpatterns at once.
In the Wolfram Language, this is done with StringCases.
In[97]:=
Click for copyable input
Out[98]=
This is similar to assigning all the matches to an array using the modifier.
The same thing is easily done with StringCases in the Wolfram Language.
In[99]:=
Click for copyable input
Out[100]=

s/.../.../

The obvious Wolfram Language version of the Perl substitution operator is StringReplace.
The default Perl behavior is to do a single replacement.
In[101]:=
Click for copyable input
Out[102]=
The modifier in Perl does global replacement of all matches.
In[103]:=
Click for copyable input
Out[103]=
Using the evaluation modifier, Perl can use subpatterns as part of the replacement. This is easily done in the Wolfram Language.
In[104]:=
Click for copyable input
Out[105]=

split(...)

The Perl command is similar to StringSplit in the Wolfram Language.
In[106]:=
Click for copyable input
Out[107]=
You can specify the number of blocks to split into in both Perl and the Wolfram Language.
In[108]:=
Click for copyable input
Out[108]=
A with capturing parentheses in the pattern, for which the captured substrings are included in the result, can be done in the Wolfram Language using rules in the second argument of StringSplit. Compared to Perl, in the Wolfram Language it is easy to then apply a function to these substrings.
In[109]:=
Click for copyable input
Out[110]//InputForm=
In[111]:=
Click for copyable input
Out[112]//InputForm=

tr/.../.../

The Perl command can be simulated using Wolfram Language StringReplace together with the appropriate list of rules.

Here is the simplest form where the characters , , and are replaced by , , and , respectively.
This generates the appropriate rules in the Wolfram Language using Thread.
In[113]:=
Click for copyable input
Out[114]=
Here is an example where the replacement list is shorter than the character list, so , , and are all replaced by .
In[115]:=
Click for copyable input
Out[116]=
Character ranges in Perl are emulated using CharacterRange in the Wolfram Language.
In[117]:=
Click for copyable input
Out[118]=
With the modifier, the surplus characters are instead deleted.
In[119]:=
Click for copyable input
Out[120]=
With the modifier, the complement of the character list is used.
In[121]:=
Click for copyable input
Out[121]=
In[122]:=
Click for copyable input
Out[122]=
The modifier squeezes down to one any run of characters translating into the same character.
You get the same effect in the Wolfram Language using Repeated ().
In[123]:=
Click for copyable input
Out[124]=

Some Examples

Some brief examples of practical uses of string patterns are presented in this section.

Highlight Patterns

This defines a 1000-base random DNA string.
In[125]:=
Click for copyable input
Out[125]=
This highlights parts of the DNA that match a certain pattern.
In[126]:=
Click for copyable input
Out[126]=
Here is the same result using a regular expression.
In[127]:=
Click for copyable input
Out[127]=

HTML Parsing

String patterns are useful for taking raw HTML and extracting information from it.

Here is the source from www.google.com.
In[128]:=
Click for copyable input
In[129]:=
Click for copyable input
Out[129]=
This extracts all the direct hyperlinks in the source.
In[130]:=
Click for copyable input
Out[130]=
This deletes everything inside tags <>.
In[131]:=
Click for copyable input
Out[131]=

Find Money

Here is some text to scan for strings that look like dollar amounts.
In[132]:=
Click for copyable input
Out[132]=
This is one way to do the search using symbolic string patterns.
In[133]:=
Click for copyable input
Out[133]=
Here is the same search using regular expressions (note that you must remember to escape the dollar sign).
In[134]:=
Click for copyable input
Out[134]=
There is also a built-in pattern object, NumberString, for this particular situation.
In[135]:=
Click for copyable input
Out[135]=

Find Text in Files

Here is a very simple grep-like function for finding lines in a text file containing text matching a given pattern.
In[136]:=
Click for copyable input
This creates a sample text file.
In[137]:=
Click for copyable input
Out[137]=
This returns the line numbers and lines in containing any digit characters.
In[138]:=
Click for copyable input
Out[138]//TableForm=
This finds lines containing as a standalone word.
In[139]:=
Click for copyable input
Out[139]//TableForm=

Tips and Tricks for Efficient Matching

This section addresses some issues involving efficiency in string pattern matching.

StringExpression versus RegularExpression

Since a string pattern written in Wolfram Language syntax is immediately translated to a regular expression and then compiled and cached, there is very little overhead in using the Wolfram Language syntax as opposed to the regular expression syntax directly. An exception to this happens when many different patterns are used a few times; in that case the overhead might be noticeable.

Conditions and PatternTests

If a pattern contains Condition () or PatternTest () statements, the general Wolfram Language evaluator must be invoked during the match, thus slowing it down. If a pattern can be written without such constructs, it will typically be faster.
In[140]:=
Click for copyable input
In[141]:=
Click for copyable input
Out[141]=
In[142]:=
Click for copyable input
Out[142]=

Avoid Nested Quantifiers

Because of the nondeterministic finite automaton (NFA) algorithm used in the match, patterns involving nested quantifiers (such as and or the regular expression equivalents) can become arbitrarily slow. Such patterns can usually be "unrolled" into more efficient versions (see Friedl [2] for additional information).

Avoid Many Calls to a Function

If you are searching through a long list of strings for certain matches, it is more efficient to feed the whole list to a string function at once, rather than using something like Select and StringMatchQ (see the earlier dictionary example for an illustration). Here is another example that generates a list of 2000 strings with 10 characters each and searches for the strings that start with an and contain as a substring.
In[143]:=
Click for copyable input
In[144]:=
Click for copyable input
Out[144]=
Here is the slower version, using Select and StringMatchQ.
In[145]:=
Click for copyable input
Out[145]=
If you instead feed the whole list to StringMatchQ at once, it will be much faster. Then Pick can be used to extract the wanted elements.
In[146]:=
Click for copyable input
Out[146]=
Alternatively, you could use StringCases, which is also fast. Note that you need to anchor the pattern using StartOfString to ensure that the is at the start (the EndOfString is superfluous in this particular case).
In[147]:=
Click for copyable input
Out[147]=

Rewrite General Expression Searches as String Searches

Because the string-matching algorithm is different than the algorithm the Wolfram Language uses for general expression matching (string matching can assume a finite alphabet and a flat structure, for instance), there are cases where it is advantageous to translate a normal expression-matching problem to a string-matching problem. A typical case is matching a long list of symbols against a pattern involving several occurrences of and .

As an example, assume you want to find primes (after prime number 1000000, say) that have at least four identical digits. Using ordinary pattern matching, it could be accomplished like this.
In[148]:=
Click for copyable input
Out[148]=
By converting the list of integers to a string, you can use string matching instead.
In[149]:=
Click for copyable input
Out[149]=
By using the previous tips of using Pick or StringCases, you can speed it up even more.
In[150]:=
Click for copyable input
Out[150]=
In[151]:=
Click for copyable input
Out[151]=
For long sequences, the difference can be significant.
In[152]:=
Click for copyable input
In[153]:=
Click for copyable input
Out[153]=
In[154]:=
Click for copyable input
Out[154]=
In[155]:=
Click for copyable input
In[156]:=
Click for copyable input
Out[156]=
In[157]:=
Click for copyable input
Out[157]=

Implementation Details

String pattern matching in the Wolfram Language is built on top of the PCRE (Perl Compatible Regular Expressions) library by Philip Hazel [1].

In some cases the pre-5.1 Wolfram Language algorithms are used (for example, when the pattern is just a single, literal string).

Any symbolic string pattern is first translated to a regular expression. You can see this translation by using the internal function.
In[158]:=
Click for copyable input
Out[158]//InputForm=

The first element returned is the regular expression, while the rest of the elements have to do with conditions, replacement rules, and named patterns.

The regular expression is then compiled by PCRE, and the compiled version is cached for future use when the same pattern appears again. The translation from symbolic string pattern to regular expression only happens once.

Wolfram Language conditions in the pattern are handled by external call-outs from the PCRE library to the Wolfram Language evaluator, so this will slow down the matching.

Explicit RegularExpression objects embedded into a general string pattern will be spliced into the final regular expression (surrounded by noncapturing parentheses ), so the counting of named patterns can become skewed compared to what you might expect.

Because PCRE currently does not support preset character classes with characters beyond character code 255, the word and letter character classes (such as WordCharacter and LetterCharacter) only include character codes in the Unicode range 0255. Thus LetterCharacter and _?LetterQ do not give equivalent results beyond character code 255.

Because of a similar PCRE restriction, case-insensitive matching (for example, with IgnoreCase->True) will only apply to letters in the Unicode range 0127 (that is, the normal English letters and ).

References

[1] Hazel, P. "PCREPerl Compatible Regular Expressions." 2004. www.pcre.org

[2] Friedl, J. E. F. Mastering Regular Expressions, 2nd ed. O'Reilly & Associates, 2002.