为什么忽略大小写标志(re.I)在 re.sub() 中不起作用 [英] Why doesn't ignorecase flag (re.I) work in re.sub()
问题描述
来自pydoc:
re.sub = sub(pattern, repl, string, count=0, flags=0)
返回替换最左边得到的字符串字符串中模式的非重叠出现替代品repl 可以是字符串或可调用的;如果是字符串,则处理其中的反斜杠转义.如果是一个可调用的,它传递了匹配对象并且必须返回要使用的替换字符串.
re.sub = sub(pattern, repl, string, count=0, flags=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.
示例代码:
import re
print re.sub('class', 'function', 'Class object', re.I)
除非我将模式更改为类",否则不会进行替换.
No replacement is made unless I change pattern to 'Class'.
文档没有提及任何有关此限制的内容,因此我认为我可能做错了什么.
Documentation doesn't mention anything about this limitation, so I assume I may be doing something wrong.
这是怎么回事?
推荐答案
在我看来你应该这样做:
Seems to me that you should be doing:
import re
print(re.sub('class', 'function', 'Class object', flags=re.I))
没有这个,re.I
参数会被传递给 count
参数.
Without this, the re.I
argument is passed to the count
argument.
这篇关于为什么忽略大小写标志(re.I)在 re.sub() 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!