gpt4 book ai didi

python - 如何用正则表达式将此表单 : (word. Word) 替换为 (word.\nWord)?

转载 作者:行者123 更新时间:2023-12-01 23:30:59 27 4
gpt4 key购买 nike

我想编写一个 Python 代码来检查字符串是否包含类似于以下内容的内容:

  • 'word.Word' => 将其替换为 'word.\nWord'
  • smallLetter.capitalLetter => smallLeter.\nCapitalLetter.

我发现我应该使用 Python 正则表达式(实际上我不知道如何在其中编写格式!)

我尝试创建这个示例:

import re
text = 'What is the.What is thef.How did youDo that?F'
text = re.sub(r"(\.+[A-Z])", r".\n;", text)

输入:'What are you.How did you.When did youDo that?F'

输出:'What are you.\now did you.\nhen did youDo that?F'

我认为它有效,但我不想替换大写字母,我想将其保留在文本中。

例如:输入:'Hey.Wow' -> 输出:'Hey.\nWow'

最佳答案

不是匹配大写字母,而是检查它是否存在 positive-lookahead (对于具有正后视的小写字母也是如此):

\.+[A-Z]  -->  (?<=[a-z])\.(?=[A-Z])

例子:

import re

text = 'What is the.What is thef.how did you.Do that?F'
text = re.sub(r"(?<=[a-z])\.(?=[A-Z])", r".\n", text)
print(text)

将给予:

What is the.
What is thef.how did you.
Do that?F

Regex demo

关于python - 如何用正则表达式将此表单 : (word. Word) 替换为 (word.\nWord)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66259864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com