首页 > 解决方案 > 如何用正则表达式将此形式: (word.Word) 替换为 (word.\nWord)?

问题描述

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

我发现我应该使用 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'

标签: pythonregex

解决方案


而不是匹配大写字母,只需检查它是否存在正向预读(对于带有正向预读的小写字母也是如此):

\.+[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

正则表达式演示


推荐阅读