Skip to content

Commit 7dda39b

Browse files
committed
Merge pull request #8 from dex4er/flag_g
Extra g flag returns the list of all matched strings
2 parents ceae9cd + e3ad591 commit 7dda39b

3 files changed

Lines changed: 28 additions & 7 deletions

File tree

README.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,12 @@ Every **Rex** pattern as in Perl patterns allows to suffix some flags, e.g. ``re
146146
* ``u`` - re.UNICODE
147147
* ``x`` - re.VERBOSE
148148

149+
Extra flags
150+
-----------
151+
152+
Extra ``g`` flags means that **Rex** returns the list of all matched strings.
153+
154+
149155
Caching
150156
-------
151157

rex.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import re
22
import operator
3-
from six.moves import reduce
43
import six
54

65
REX_CACHE = {}
@@ -40,15 +39,20 @@ class Rex(object):
4039
'x': re.VERBOSE,
4140
}
4241

43-
def __init__(self, action, pattern, replacement='', flags=0):
42+
EXTRA_FLAGS = 'g'
43+
44+
def __init__(self, action, pattern, replacement='', flags=0, extra_flags=''):
4445
self.action = action
4546
self.pattern = pattern
4647
self.flags = flags
48+
self.extra_flags = extra_flags
4749
self.replacement = replacement
4850
self.re = re.compile(self.pattern, self.flags)
4951

5052
def __process(self, text):
5153
if self.action == 'm':
54+
if 'g' in self.extra_flags:
55+
return self.re.findall(text)
5256
result = RexMatch()
5357
match = self.re.search(text)
5458
if match is not None:
@@ -95,12 +99,17 @@ def rex(expression, text=None, cache=True):
9599
replacement = pattern[index + 1:]
96100
pattern = pattern[:index]
97101

98-
try:
99-
re_flags = [Rex.FLAGS[f] for f in expression[end + 1:]]
100-
except KeyError:
101-
raise ValueError('Bad flags')
102+
flags = 0
103+
extra_flags = ''
104+
for f in expression[end + 1:]:
105+
if f in Rex.FLAGS:
106+
flags |= Rex.FLAGS[f]
107+
elif f in Rex.EXTRA_FLAGS:
108+
extra_flags += f
109+
else:
110+
raise ValueError('Bad flags')
102111

103-
rex_obj = Rex(action, pattern, replacement, reduce(operator.or_, re_flags, 0))
112+
rex_obj = Rex(action, pattern, replacement, flags, extra_flags)
104113
if cache:
105114
REX_CACHE[expression] = rex_obj
106115

test_rex.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,12 @@ def test_m_false_call():
122122
assert not r("Aa 9-9 xx")
123123

124124

125+
def test_m_g():
126+
assert (("Aa 9-9 88 xx" == rex('/(\d)/g')) == ['9', '9', '8', '8'])
127+
assert (("Aa 9-9 88 xx" == rex('/([aA])/g')) == ['A', 'a'])
128+
assert (("Aa 9-9 88 xx" == rex('/(ttt)/g')) == [])
129+
130+
125131
def test_s():
126132
s = ("This is a cat" == rex('s/cat/dog/'))
127133
assert s == 'This is a dog'

0 commit comments

Comments
 (0)