简体   繁体   中英

Why it doesn't work in Python regular expression

str = 'an simple example'
print re.sub(r'^AN', 'A', str, re.I)

It was expected print A simple example
but, it still print an simple example

python version 2.7(Fedora x84_64)

The last parameter of re.sub is a count of the replacements to do. If you want to replace with options, compile the regex:

>>> r = re.compile(r'^AN', re.IGNORECASE)
>>> my_str = 'AN simple example'
>>> r.sub('A', my_str)
'A simple example'

As bereal pointed out, the third parameter is the count of replacements to do.

The whole definition of re.sub is

def sub(pattern, repl, string, count=0, flags=0):

So instead of compiling the regex, you can use

print re.sub(r'^AN', 'A', str, 0, re.I)

or with a named parameter:

print re.sub(r'^AN', 'A', str, flags=re.I)

BTW, str is already a python function (but no reserved keyword), so redefining str could lead to strange problems.

If you want insensitive substitution use the insensitive option:

str = 'an simple example'
print re.sub(r'(?i)an', 'A', str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM