Function Repository Resource:

ToRegularExpression

Source Notebook

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

Contributed by: Taliesin Beynon

ResourceFunction["ToRegularExpression"][patt]

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

Examples

Basic Examples (2) 

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

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

Use the regular expression:

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

Scope (6) 

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

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

Create a regular expression for specified characters:

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

Create a regular expression involving alternatives:

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

Create a regular expression with an exception:

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

Create a regular expression for a date pattern:

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

Create a regular expression for a grammar rule pattern:

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 07 February 2019

License Information