diff options
-rw-r--r-- | pyparsing.py | 18 | ||||
-rw-r--r-- | unitTests.py | 27 |
2 files changed, 44 insertions, 1 deletions
diff --git a/pyparsing.py b/pyparsing.py index cdbf398..3ea7660 100644 --- a/pyparsing.py +++ b/pyparsing.py @@ -2846,7 +2846,23 @@ class Regex(Token): Return Regex with an attached parse action to transform the parsed
result as if called using C{re.sub(expr, repl, string)}.
"""
- return self.addParseAction(lambda s, l, t: self.re.sub(repl, t[0]))
+ if self.asGroupList:
+ warnings.warn("cannot use sub() with Regex(asGroupList=True)",
+ SyntaxWarning, stacklevel=2)
+ raise SyntaxError()
+
+ if self.asMatch and callable(repl):
+ warnings.warn("cannot use sub() with a callable with Regex(asMatch=True)",
+ SyntaxWarning, stacklevel=2)
+ raise SyntaxError()
+
+ if self.asMatch:
+ def pa(tokens):
+ return tokens[0].expand(repl)
+ else:
+ def pa(tokens):
+ return self.re.sub(repl, tokens[0])
+ return self.addParseAction(pa)
class QuotedString(Token):
r"""
diff --git a/unitTests.py b/unitTests.py index 56a6cf2..9966012 100644 --- a/unitTests.py +++ b/unitTests.py @@ -1740,12 +1740,39 @@ class RegexSubTest(ParseTestCase): print_(result)
assert result == '<h1>This is the main heading</h1>\n<h2>This is the sub-heading</h2>', "incorrect Regex.sub result with re string"
+ print_("test sub with re string (Regex returns re.match)")
+ expr = pp.Regex(r"([Hh]\d):\s*(.*)", asMatch=True).sub(r"<\1>\2</\1>")
+ result = expr.transformString("h1: This is the main heading\nh2: This is the sub-heading")
+ print_(result)
+ assert result == '<h1>This is the main heading</h1>\n<h2>This is the sub-heading</h2>', "incorrect Regex.sub result with re string"
+
print_("test sub with callable that return str")
expr = pp.Regex(r"<(.*?)>").sub(lambda m: m.group(1).upper())
result = expr.transformString("I want this in upcase: <what? what?>")
print_(result)
assert result == 'I want this in upcase: WHAT? WHAT?', "incorrect Regex.sub result with callable"
+ try:
+ expr = pp.Regex(r"<(.*?)>", asMatch=True).sub(lambda m: m.group(1).upper())
+ except SyntaxError:
+ pass
+ else:
+ assert False, "failed to warn using a Regex.sub(callable) with asMatch=True"
+
+ try:
+ expr = pp.Regex(r"<(.*?)>", asGroupList=True).sub(lambda m: m.group(1).upper())
+ except SyntaxError:
+ pass
+ else:
+ assert False, "failed to warn using a Regex.sub() with asGroupList=True"
+
+ try:
+ expr = pp.Regex(r"<(.*?)>", asGroupList=True).sub("")
+ except SyntaxError:
+ pass
+ else:
+ assert False, "failed to warn using a Regex.sub() with asGroupList=True"
+
class CountedArrayTest(ParseTestCase):
def runTest(self):
from pyparsing import Word,nums,OneOrMore,countedArray
|