I am getting different results based on whether I precompile a regular expression:
>>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean')
' Bean'
>>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE)
'Mr Bean'
The Python documentation says Some of the functions are simplified versions of the full featured methods for compiled regular expressions. However it also claims RegexObject.sub() is Identical to the sub() function.
So what is going on here?
re.sub() can't accept the re.IGNORECASE, it appears.
The documentation states:
sub(pattern, repl, string, count=0)Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.
Using this works in its place, however:
re.sub("(?i)mr", "", "Mr Bean")
the module level sub() call doesn't accept modifiers at the end. thats the "count" argument - the maximum number of pattern occurrences to be replaced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With