为什么我的 re.sub 没有使用我的正则表达式查找所有实例?
Why isn't my re.sub finding all instances using my regex?
我在 Windows 10 上使用 Python 3.10 并尝试进行以下搜索:
re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r' ', 'JohnnyB Cool & JoeCool')
'JohnnyB Cool & Joe Cool'
如果我只使用“JohnnyB Cool”,“B”前面会有一个 space。
re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r' ', 'JohnnyB Cool')
'Johnny B Cool'
为什么第一次搜索时没有替换“JohnnyB”?我也试过:
re.sub(r'(.*)([A-Z]+[a-z]+)([A-Z])', r' ', '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
解释:
\B
匹配 \b
不相邻的另一个单词字符
[A-Z]
匹配大写字母
我在 Windows 10 上使用 Python 3.10 并尝试进行以下搜索:
re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r' ', 'JohnnyB Cool & JoeCool')
'JohnnyB Cool & Joe Cool'
如果我只使用“JohnnyB Cool”,“B”前面会有一个 space。
re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r' ', 'JohnnyB Cool')
'Johnny B Cool'
为什么第一次搜索时没有替换“JohnnyB”?我也试过:
re.sub(r'(.*)([A-Z]+[a-z]+)([A-Z])', r' ', '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
解释:
\B
匹配\b
不相邻的另一个单词字符[A-Z]
匹配大写字母