Skip to content

Refactor: Extract to_re_flags() #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions rex.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,27 @@ def __unicode__(self):
return six.u(self[0]) if self[0] else u''


RE_FLAGS = {
'd': re.DEBUG,
'i': re.IGNORECASE,
'l': re.LOCALE,
'm': re.MULTILINE,
's': re.DOTALL,
'u': re.UNICODE,
'x': re.VERBOSE,
}


def to_re_flags(s):
"""Convert string suffixes to numeric flags of re module."""
try:
re_flags = [RE_FLAGS[f] for f in s]
except KeyError:
raise ValueError('Bad flags')
return reduce(operator.or_, re_flags, 0)


class Rex(object):
FLAGS = {
'd': re.DEBUG,
'i': re.IGNORECASE,
'l': re.LOCALE,
'm': re.MULTILINE,
's': re.DOTALL,
'u': re.UNICODE,
'x': re.VERBOSE,
}

def __init__(self, action, pattern, replacement='', flags=0):
self.action = action
Expand Down Expand Up @@ -95,19 +106,16 @@ 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')

rex_obj = Rex(action, pattern, replacement, reduce(operator.or_, re_flags, 0))
flags = to_re_flags(expression[end + 1:])
rex_obj = Rex(action, pattern, replacement, flags)
if cache:
REX_CACHE[expression] = rex_obj

if text is not None:
return text == rex_obj
else:
return rex_obj

rex.group = RexMatch()


Expand Down