简体   繁体   English

为什么它在Python正则表达式中不起作用

[英]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 期待印刷A simple example
but, it still print an simple example 但是,它仍然显示an simple example

python version 2.7(Fedora x84_64) python版本2.7(Fedora x84_64)

The last parameter of re.sub is a count of the replacements to do. re.sub的最后一个参数是要执行的替换计数。 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. 正如bereal指出的那样,第三个参数是要执行的替换计数。

The whole definition of re.sub is re.sub的整个定义是

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. 顺便说一句, str已经是一个python函数(但没有保留关键字),因此重新定义str可能会导致奇怪的问题。

If you want insensitive substitution use the insensitive option: 如果要使用不敏感替换,请使用不敏感选项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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