Wolfram Computation Meets Knowledge

ToRegularExpression

Contributed by: Taliesin Beynon

Convert a string expression or a related object to a regular expression

ResourceFunction["ToRegularExpression"][patt]

gives a string containing a regular expression that matches the string pattern patt.

Examples

Basic Examples

Construct a regular expression that matches strings starting from a specified character:

In[1]:=
regex = ResourceFunction["ToRegularExpression"]["A" ~~ __]
Out[1]=

Use the regular expression:

In[2]:=
StringMatchQ["Abc", RegularExpression[regex]]
Out[2]=
In[3]:=
StringMatchQ["Xbc", RegularExpression[regex]]
Out[3]=

Scope

Create and use a regular expression that matches a string expression:

In[4]:=
ResourceFunction["ToRegularExpression"]["a" ~~ __]
Out[4]=
In[5]:=
StringMatchQ["abc", RegularExpression[%]]
Out[5]=
In[6]:=
StringMatchQ["xyz", RegularExpression[%%]]
Out[6]=

Create a regular expression for specified characters:

In[7]:=
ResourceFunction["ToRegularExpression"][Characters["abc"] ..]
Out[7]=
In[8]:=
StringMatchQ["abca", RegularExpression[%]]
Out[8]=
In[9]:=
StringMatchQ["abcx", RegularExpression[%%]]
Out[9]=

Create a regular expression involving alternatives:

In[10]:=
ResourceFunction["ToRegularExpression"][("aa" | "bb" | "cc") ..]
Out[10]=
In[11]:=
StringMatchQ["aabb", RegularExpression[%]]
Out[11]=
In[12]:=
StringMatchQ["aabc", RegularExpression[%%]]
Out[12]=

Create a regular expression with an exception:

In[13]:=
ResourceFunction["ToRegularExpression"][
 Except["b", RegularExpression["[a-z]"]] ..]
Out[13]=
In[14]:=
StringMatchQ["acd", RegularExpression[%]]
Out[14]=
In[15]:=
StringMatchQ["abc", RegularExpression[%%]]
Out[15]=

Create a regular expression for a date pattern:

In[16]:=
ResourceFunction["ToRegularExpression"][
 DatePattern[{"Day", "Month", "Year"}]]
Out[16]=
In[17]:=
StringMatchQ["31/12/2019", RegularExpression[%]]
Out[17]=
In[18]:=
StringMatchQ["31/13/2019", RegularExpression[%%]]
Out[18]=

Create a regular expression for a grammar rules pattern:

In[19]:=
ResourceFunction["ToRegularExpression"][AnyOrder["1", "2", "3"]]
Out[19]=
In[20]:=
StringMatchQ["321", RegularExpression[%]]
Out[20]=
In[21]:=
StringMatchQ["12", RegularExpression[%%]]
Out[21]=

Resource History