simplere /

Filename Size Date modified Message
simplere
test
106 B
5.0 KB
33 B
1.4 KB
116 B

A simplified interface to Python's regular expression (re) string search that tries to eliminate steps and provide simpler access to results. As a bonus, also provides compatible way to access Unix glob searches.

Usage

Python regular expressions are powerful, but the language's lack of an en passant assignment requires a preparatory motion and then a test:

import re

match = re.search(pattern, some_string)
if match:
print match.group(1)


With simplere, you can do it in fewer steps:

from simplere import Re

if some_string in Re(pattern):
print Re._[1]


pattern here would typically be a string, but it can also be a pre-existing compiled regular expression. Re objects are memoized for efficiency, so they so they're only compiled once, regardless of how many times they're mentioned in the program.

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 Re pattern is an intensionally defined set (namely "all strings matching the pattern"). This order often makes excellent sense whey you have a clear intent for the test. For example, "is the given string within the set of all legitimate commands?"

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.

If you prefer the more traditional re calls:

if Re(pattern).search(some_string):
print Re._[1]


Re works even better with named pattern components, which are exposed as attributes of the returned object:

person = 'John Smith 48'
if person in Re(r'(?P<name>[\w\s]*)\s+(?P<age>\d+)'):
print Re._.name, "is", Re._.age, "years old"
else:
print "don't understand '{}'".format(person)


One trick being used here is that the returned object is not a pure _sre.SRE_Match that Python's re module returns. Nor is it a subclass. (That class appears to be unsubclassable.) Thus, regular expression matches return a proxy object that exposes the match object's numeric (positional) and named groups through indices and attributes. If a named group has the same name as a match object method or property, it takes precedence. Either change the name of the match group or access the underlying property thus: x._match.property

It's possible also to loop over the results:

for found in Re('pattern (\w+)').finditer('pattern is as pattern does'):
print found[1]


Or collect them all in one fell swoop:

found = Re('pattern (\w+)').findall('pattern is as pattern does')


Pretty much all of the methods and properties one can access from the standard re module are available.

Bonus: Globs

Regular expressions are wonderfuly powerful, but sometimes the simpler Unix glob is works just fine. As a bonus, simplere also provides simple glob access.:

if 'globtastic' in Glob('glob*'):
print "Yes! It is!"
else:
raise ValueError('YES IT IS')


Partial Credit

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.:

match = re.match(r'(?P<word>this)', 'this is a string')
match = ReMatch(match)
if match:
print match.group(1)    # still works
print match[1]          # same thing
print match.word        # same thing, with logical name


Notes

• Automated multi-version testing is managed with the wonderful pytest and tox. simplere is successfully packaged for, and tested against, all late-model verions of Python: 2.6, 2.7, 3.2, and 3.3, as well as PyPy 1.9 (based on 2.7.2).
• simplere is one part of a larger effort to add intensional sets to Python. The intensional package contains a parallel implementation of Re, among many other things.

Installation

pip install -U simplere

python3.3 -m easy_install --upgrade simplere