为什么我的 re.sub 没有使用我的正则表达式查找所有实例?



我在Windows 10上使用Python 3.10,并尝试以下搜索:

re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r'1 2', 'JohnnyB Cool & JoeCool')
'JohnnyB Cool & Joe Cool'

如果我只使用";JohnnyB Cool";,";B";在它之前得到一个空格。

re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r'1 2', 'JohnnyB Cool')
'Johnny B Cool'

为什么";JohnnyB";在第一次搜索中被替换?我也试过:

re.sub(r'(.*)([A-Z]+[a-z]+)([A-Z])', r'1 2 3', 'JohnnyB Cool & JoeCool')
'JohnnyB Cool &  Joe Cool'

为了明确起见,我希望最终的答案是Johnny B Cool & Joe Cool

您可以使用以下python代码:

>>> import re
>>> s = 'JohnnyB Cool & JoeCool'
>>> print (re.sub(r'B[A-Z]', r' g<0>', s))
Johnny B Cool & Joe Cool

RegEx演示

解释:

  • Bb不匹配的地方匹配,即与另一个单词字符相邻
  • [A-Z]匹配大写字母

最新更新