Regular Expressions

Regular Expressions – regexps or regexes – are powerful means of pattern-recognizing across strings. They are also performant. The standard python library re lets you compile your pattern match stings, and it is highly optimized at string tokenizing from then on.

The problem with regular expressions is the syntax is dense.

Part 1 - Constructing Expressions

To this goal, our regexp module includes a number of helpful functions for assembling complex regular expressions:

This begins with the workhorse:

  • Group() – ensures a string is wrapped in the right kind of parens

Then a few other ways of calling it:

  • Capture() – wraps Group() to make a capture or named capture
  • Optional() – wraps Group() to make a non-capturing group
  • BackRef() – wraps Group() to make a look-behind reference

There’s also:

  • Or() – converts list args into OR-separated non-capturing groups

Example

Consider parsing a date string, like '2023-08-20'. Or maybe the user gives us only '2023-08' or even just '2023'.

Let’s build a complex regular expression that matches all of these.

In general, importing * is unhygienic python, but in this case we’re going to recommend it:

from base.regexp import *

Then:

# "maybe some spaces, dash-or-slash, then maybe some spaces"
DATESEP         = r'\s*[-/]\s*'
# "any of these symbols, or the end of the string"
LOOKAHEADSEP    = Group('[t\s:+=/\-\.]|$', GROUPTYPE_LOOK_AHEAD)

# "digits" -- 1-2 digit and 4-digit versions
DIGIT12         = r'(\d\d?)'
DIGIT4          = r'(\d\d\d\d)'

# now we define what a year, a month, and a day look like
YEAR            = Capture(DIGIT4, name='year')
MONTH12         = Capture(DIGIT12, name='month')
DAY12           = Capture(DIGIT12, name='day')

# put it together:
DATE            = YEAR + Optional(
    DATESEP + MONTH12 + Optional(DATESEP + DAY12)
) + LOOKAHEADSEP

This gives us DATE which is just a string, with a properly-formatted regular expression inside.

From here, we can use Python’s standard re library:

import re
rem             = re.match(DATE, '2023-08-20')
print(rem.groupdict())

Like magic, Python outputs:

{'year': '2023', 'month': '08', 'day': '20'}

Part 2 – Grouper and MultiGrouper

We also offer classes Grouper() and MultiGrouper() that apply regular expressions for you and only return the results.

Grouper is like a thin wrapper around re.match(). This should output the exact same result as the last example:

date             = Grouper(DATE)
print(date('2023-08-20'))

There is an optional flag on Grouper that constrains matches to only at the start of the string, anywhere in the string (default), or only if the pattern matches the entire string.

picky_date       = Grouper(DATE, GROUPERMODE_TOTAL)

MultiGrouper takes a list of patterns instead of a single pattern. It also accepts a flag to say whether you want it to accept the first matching pattern, or whether all patterns should be tested and the one that matches the most number of named groups should be the one kept (default).

To see these classes in action, take a look at the CommonParser class in base/commonera.py. Our date-matching expression above is lifted verbatim from this code.