相关疑难解决方法(0)

为什么正则表达式引擎允许/在输入字符串的末尾自动尝试匹配?

注意:
*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)

也许不用说,只有当所讨论的正则表达式匹配空字符串时(例如,默认情况下正则表达式/被配置为报告零长度匹配),这样的匹配尝试才会成功. …

regex language-agnostic

23
推荐指数
2
解决办法
529
查看次数

re.sub(".*",","(替换)","text")在Python 3.7上加倍替换

在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)

怎么了?如何解决?

python python-regex

10
推荐指数
1
解决办法
387
查看次数

标签 统计

language-agnostic ×1

python ×1

python-regex ×1

regex ×1