我如何编写一个正则表达式来删除分号之后的单词,直到它到达第一个句点标记?
例如:
try to be nice; underastand people. start fresh.
我想去掉“懂人”,有类似的东西
try to be nice. start fresh
这是我的正则表达式,但遗憾的是它不起作用:
sentence = ''.join(re.sub(r';.*?.', '.', sentence))
谢谢!
请您参考如下方法:
您忘记转义点:r';.*?\.'。此外,这里不需要加入任何东西,你将一个字符串传递给re.sub,然后你会得到一个字符串。
A r';[^.]+' 正则表达式似乎更好,因为它会匹配 ; 和除文字点以外的 1+ 个字符(所以,你可以替换为空字符串):
import re
sentence = "try to be nice; underastand people. start fresh."
sentence = re.sub(r';[^.]+', '', sentence)
print(sentence)
# => try to be nice. start fresh.
参见 Python demo
