tags:

views:

59

answers:

3

I know that re.sub(pattern, repl,text) can substitute when pattern matches, and then return the substitute my code is

text = re.sub(pattern, repl, text1)

I have to define another variable to to check whether it modified

text2 = re.sub(pattern, repl, text1)
matches = text2 != text1
text1 = text2

and, it has issues, e.g. text1='abc123def' , pattern = '(123|456)', repl = '123', after replace , it is same, so matches is false, but it actually matches.

A: 

The repl parameter can also be a function which takes an RE match object and returns what the replacement should be; this function is not called if the text doesn't match. You could use that to do what you needed then just return a constant string you want to replace it with. This would cut down on an unneeded second check against the RE.

This is true, however the `re.subn` provides the desired functionality with less clutter than a callable `repl` parameter.
ΤΖΩΤΖΙΟΥ
+8  A: 

Use re.subn

Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

and then check the number of replacements that were made. For example:

text2, numReplacements = re.subn(pattern, repl, text1)
if numReplacements:
    # did match
else:
    # did not match
AndiDog
A: 

"Whether string contains numbers":

for text1 in ('abc123def', 'adsafasdfafdsafqw', 'fsadfoi81we'):
    print("Text %s %s numbers." %
          ((text1, )  + (
              ('does not contain',) if not any(c.isdigit() for c in text1)
               else ('contains',))
           ))
Tony Veijalainen