Python regular expressions are powerful, but the language's lack of an *en passant*
assignment requires a preparatory
if some_string in Re(pattern):
``pattern`` here would typically be a string, but it can also be a pre-existing
compiled regular expression. ``Re`` objects are `memoized
<http://en.wikipedia.org/wiki/Memoization>`_ for efficiency, so they so they're
only compiled once, regardless of how many times they're mentioned in the
Note that the ``in`` test turns the sense of the matching around (compared to
the standard ``re`` module). It asks "is the given string *in*
the set of items this pattern describes?" To be fancy, the
Second, the ``in`` test had the side effect of setting the underscore
name ``_`` to the result. Python doesn't support *en passant* assignment--apparently,
-no matter how hard you try, or how much introspection you use. Thus
-you can't both test and collect results in the same motion, even though that's
-often exactly appropriate. Collecting them in a class variable is a fallback.
+no matter how hard you try, or how much introspection you use. This makes it
+harder to both test and collect results in the same motion, even though that's
+often exactly appropriate. Collecting them in a class variable is a fallback
+strategy (see the *En Passant* section below for a slicker one).
If you prefer the more traditional ``re`` calls::
raise ValueError('YES IT IS')
If you have existing code that already uses ``re`` regular expressions
and you want to ease into using ``simplere``, ``ReMatch`` objects can
-simply wrap the ``_sre.SRE_Match`` objects that ``re`` returns.::
+simply wrap Python's native``_sre.SRE_Match`` objects (the things that ``re``
- match = re.match(r'(?P<word>th
is)', 'this is a string')
+ match = re.match(r'(?P<word>ths)', 'this is a string')
print match.group(1) # still works
print match # same thing
print match.word # same thing, with logical name
+But that's a huge amount of boiler plate for a simple test, right? So ``simplere``
+also uses an *en passant* trick of redefining the division operation::
+ if match / re.search(r'(?P<word>th.s)', 'this is a string'):
+ assert match == 'this'
+ assert match.word == 'this'
+ assert match.group(1) == 'this'
+This uses the pre-delcared ``match`` object and the division operator (``/``)
+the result of the search.
+If the ``re`` operation fails, the resulting object is guaranteed to have
+a ``False``-like boolean value, so that it will fall through conditional tests.
+If you prefer the look of the less-than (``<``) or less-than-or-equal (``<=``),
+as indicators that ``match`` takes the value of the following function call, they
+are supported as aliases of the division operation (``/``). You may define your
+own match objects, and can use them on memoized ``Re`` objects too. Putting
+a few of these optional things together::
+ answer = Match() # need to do this just once
+ if answer < Re(r'(?P<word>th..)').search('and that goes there'):
+ assert answer.word == 'that'