This is documentation for Mathematica 4, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
Wolfram Research, Inc.

Operations on StringsCharacters in Strings

2.7.3 String Patterns

You can use the standard Mathematica equality test == to test whether two strings are identical. Sometimes, however, you may want to find out whether a particular string matches a certain string pattern.

Mathematica allows you to define string patterns which consist of ordinary strings in which certain characters are interpreted as special "metacharacters". You can then use the function StringMatchQ to find out whether a particular string matches a string pattern you have defined. You should realize however that string patterns have nothing to do with the ordinary Mathematica patterns for expressions that were discussed in Section 2.3.

Matching strings.

The character * can be used in a string pattern as a metacharacter to stand for any sequence of alphanumeric characters. Thus, for example, the string pattern "a*b" would match any string which begins with an a, ends with a b, and has any number of alphanumeric characters in between. Similarly, "a*b*" would match any string that starts with a, and has any number of other characters, including at least one b.

The string matches the string pattern you have given.

In[1]:= StringMatchQ["aaaaabbbbcccbbb", "a*b*"]


The way * is used in Mathematica string patterns is analogous to the way it is used for filename patterns in many operating systems. Mathematica however provides some other string pattern metacharacters that are tailored to matching different classes of Mathematica symbol names.

Metacharacters used in string patterns.

In Mathematica there is a general convention that only built-in names should contain upper-case characters. Assuming that you follow this convention, you can use @ as a metacharacter to set up string patterns which match names you have defined, but avoid matching built-in names.

Options for matching strings.

These strings do not match.

In[2]:= StringMatchQ["platypus", "paltypus"]


Allowing for spelling correction, these strings are considered to match.

In[3]:= StringMatchQ["platypus", "paltypus",

SpellingCorrection -> True]


These strings match when lower- and upper-case letters are treated as equivalent.

In[4]:= StringMatchQ["AAaaBBbb", "a*b*", IgnoreCase -> True]


Operations on StringsCharacters in Strings