Commits

Jonathan Eunice  committed 7aef818

fixed bug in wrapping of sub and subn calls;

  • Participants
  • Parent commits 4ba620b

Comments (0)

Files changed (3)

 
 setup(
     name='simplere',
-    version='0.21',
+    version='0.22',
     author='Jonathan Eunice',
     author_email='jonathan.eunice@gmail.com',
     description='Simpler, cleaner access to regular expressions. Globs too.',

File simplere/core.py

 _PY3 = sys.version_info[0] > 2
 if _PY3:
     basestring = str
+    
+
 
 class ReMatch(object):
     """
     def __getitem__(self, index):
         return self._match.group(index)
 
+
+function_type = type(lambda: True)   # define our own because not def'd in py26
+
+def is_function(obj):
+    """
+    Determines: Is obj a function?
+    """
+    return isinstance(obj, function_type)
+
+def regrouped(f):
+    """
+    Takes a function f that is supposed to get _sre.SRE_Match objects and
+    wraps each of those with a ReMatch proxy. If not a function (ie, probably
+    a string, then just return it.)
+    """
+    if not is_function(f):
+        return f
+    
+    def regrouped_fn(match):
+        return f(ReMatch(match))
+    
+    return regrouped_fn
+
 class Re(with_metaclass(MementoMetaclass, object)):
 
     # convenience copy of re flag constants
     def split(self, *args, **kwargs):
         return self.re.split(*args, **kwargs)
     
-    def sub(self, *args, **kwargs):
-        return self.re.sub(*args, **kwargs)
+    def sub(self, repl, *args, **kwargs):
+        return self.re.sub(regrouped(repl), *args, **kwargs)
     
-    def subn(self, *args, **kwargs):
-        return self.re.subn(*args, **kwargs)
+    def subn(self, repl, *args, **kwargs):
+        return self.re.subn(regrouped(repl), *args, **kwargs)
     
     def escape(self, *args, **kwargs):
         return self.re.escape(*args, **kwargs)

File test/test.py

     found = Re(r'pattern (\w+)').findall('pattern is as pattern does')
     assert found == 'is does'.split()
     
+def test_regrouping():
+    sentence = "you've been a bad boy"
+    pattern = r'(?P<word>bad)'
+    re_pat = Re(pattern)
+    
+    repl = lambda m: m.word.upper() # note use of attributes
+    
+    newsent = re_pat.sub(repl, sentence)
+    assert newsent == "you've been a BAD boy"
+    
+    
 def test_memoization():    
     testpat  = Re(r'\b(s\w*)\b')
     testpat1 = Re(r'\b(s\w*)\b')