为什么我的re.sub不使用我的正则态度来查找所有实例?

发布于 2025-01-19 15:45:13 字数 551 浏览 2 评论 0原文

我在 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 &乔酷。

I'm using Python 3.10 on Windows 10 and trying the search below:

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

If I use just "JohnnyB Cool", the "B" gets a space before it.

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

Why isn't the "JohnnyB" substituted in the first search? I've also tried:

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

To be clear, I want the final answer to be, Johnny B Cool & Joe Cool.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不咬妳我踢妳 2025-01-26 15:45:13

您可以使用以下 python 代码:

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

RegEx 演示

说明:

  • \B 匹配 \b 不匹配的地方,即与另一个单词字符相邻的
  • [AZ] 匹配大写字母

You may use this python code:

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

RegEx Demo

Explanation:

  • \B matches where \b doesn't i.e. adjacent to another word character
  • [A-Z] matches an uppercase letter
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文