Skip to content

Instantly share code, notes, and snippets.

@johanlindberg
Created June 2, 2010 18:27
Show Gist options
  • Save johanlindberg/422771 to your computer and use it in GitHub Desktop.
Save johanlindberg/422771 to your computer and use it in GitHub Desktop.
# Experimental extensions to Python's re module.
import re
def int_class_expansion(match):
return "(%s)" % \
('|'.join(reversed( [str(x) for x \
in xrange(int(match.group(1)),
int(match.group(2))+ 1)] )))
int_class_rule = ( r"\[(\d+)\.\.(\d+)\]", int_class_expansion)
rules = [int_class_rule,]
def expand(pattern):
result = pattern
for rule in rules:
match = re.search(rule[0], result)
while match:
result = result[:match.start()] + \
rule[1](match) + \
result[match.end():]
match = re.search(rule[0], result)
return result
def match(pattern, string, flags=0):
return re.match(expand(pattern), string, flags)
def search(pattern, string, flags=0):
return re.search(expand(pattern), string, flags)
#
@johanlindberg
Copy link
Author

I re-read Staffan's post and realized that he actually specifies that it should be greedy so my example above is clearly wrong. I've updated the code to make it behave as it should:

m = extre.match(r'([0..255].){3}[0..255]', '123.125.126.107')
m.group() '123.125.126.107'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment