diff --git a/README.rst b/README.rst index a7f3974..f84f2db 100644 --- a/README.rst +++ b/README.rst @@ -146,6 +146,12 @@ Every **Rex** pattern as in Perl patterns allows to suffix some flags, e.g. ``re * ``u`` - re.UNICODE * ``x`` - re.VERBOSE +Extra flags +----------- + +Extra ``g`` flags means that **Rex** returns the list of all matched strings. + + Caching ------- diff --git a/rex.py b/rex.py index 16ac149..eb07165 100644 --- a/rex.py +++ b/rex.py @@ -1,6 +1,5 @@ import re import operator -from six.moves import reduce import six REX_CACHE = {} @@ -40,15 +39,20 @@ class Rex(object): 'x': re.VERBOSE, } - def __init__(self, action, pattern, replacement='', flags=0): + EXTRA_FLAGS = 'g' + + def __init__(self, action, pattern, replacement='', flags=0, extra_flags=''): self.action = action self.pattern = pattern self.flags = flags + self.extra_flags = extra_flags self.replacement = replacement self.re = re.compile(self.pattern, self.flags) def __process(self, text): if self.action == 'm': + if 'g' in self.extra_flags: + return self.re.findall(text) result = RexMatch() match = self.re.search(text) if match is not None: @@ -95,12 +99,17 @@ def rex(expression, text=None, cache=True): replacement = pattern[index + 1:] pattern = pattern[:index] - try: - re_flags = [Rex.FLAGS[f] for f in expression[end + 1:]] - except KeyError: - raise ValueError('Bad flags') + flags = 0 + extra_flags = '' + for f in expression[end + 1:]: + if f in Rex.FLAGS: + flags |= Rex.FLAGS[f] + elif f in Rex.EXTRA_FLAGS: + extra_flags += f + else: + raise ValueError('Bad flags') - rex_obj = Rex(action, pattern, replacement, reduce(operator.or_, re_flags, 0)) + rex_obj = Rex(action, pattern, replacement, flags, extra_flags) if cache: REX_CACHE[expression] = rex_obj diff --git a/test_rex.py b/test_rex.py index 730fc73..ab642a7 100644 --- a/test_rex.py +++ b/test_rex.py @@ -122,6 +122,12 @@ def test_m_false_call(): assert not r("Aa 9-9 xx") +def test_m_g(): + assert (("Aa 9-9 88 xx" == rex('/(\d)/g')) == ['9', '9', '8', '8']) + assert (("Aa 9-9 88 xx" == rex('/([aA])/g')) == ['A', 'a']) + assert (("Aa 9-9 88 xx" == rex('/(ttt)/g')) == []) + + def test_s(): s = ("This is a cat" == rex('s/cat/dog/')) assert s == 'This is a dog'