注意:
*Python用于说明行为,但这个问题与语言无关.
*为了该讨论的目的,假定单行只输入,因为换行(多行输入)的存在下引入变化的行为$和.认为是不可避免的手边的问题.
大多数正则表达式引擎:
接受在输入字符串[1]结束后显式尝试匹配表达式的正则表达式.
$ python -c "import re; print(re.findall('$.*', 'a'))"
[''] # !! Matched the hypothetical empty string after the end of 'a'
Run Code Online (Sandbox Code Playgroud)当找到/替换全局时,即,当查找给定正则表达式的所有非重叠匹配,并且已到达字符串的末尾时,意外地尝试再次匹配[2],如相对问题的答案中所解释的:
$ python -c "import re; print(re.findall('.*$', 'a'))"
['a', ''] # !! Matched both the full input AND the hypothetical empty string
Run Code Online (Sandbox Code Playgroud)也许不用说,只有当所讨论的正则表达式匹配空字符串时(例如,默认情况下正则表达式/被配置为报告零长度匹配),这样的匹配尝试才会成功. …
在Python 3.7(在Windows 64位上测试),使用RegEx替换字符串.*会使输入字符串重复两次!
在Python 3.7.2上:
>>> import re
>>> re.sub(".*", "(replacement)", "sample text")
'(replacement)(replacement)'
Run Code Online (Sandbox Code Playgroud)
在Python 3.6.4上:
>>> import re
>>> re.sub(".*", "(replacement)", "sample text")
'(replacement)'
Run Code Online (Sandbox Code Playgroud)
在Python 2.7.5(32位)上:
>>> import re
>>> re.sub(".*", "(replacement)", "sample text")
'(replacement)'
Run Code Online (Sandbox Code Playgroud)
怎么了?如何解决?