Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regular expression inconsistency

Tags:

python

regex

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?

like image 430
hoju Avatar asked Jul 04 '26 10:07

hoju


2 Answers

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")
like image 114
Evan Fosmark Avatar answered Jul 07 '26 01:07

Evan Fosmark


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.

like image 42
zzzeek Avatar answered Jul 07 '26 00:07

zzzeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!