[英]python 3 find a string that is not followed by a substring
我有一个看起来像这样的字符串:
line = "aaa farmer's blooper's mouse'd would've bbb"
从我的字符串行开始,如果单词以撇号或撇号+ s('s)结尾,那么我想删除撇号和s。 但是我想保持不变。
所以,我希望我的弦成为
line = "aaa farmer blooper mouse'd would've bbb"
如何使用正则表达式来完成?
使用正则表达式预见断言撇号,或者撇号+可以是仅空格字符或字符串末尾,换句话说,单词末尾或字符串末尾
import re
line = "aaa farmer's blooper's mouse'd would've bbb"
line_new = re.sub(r"'s?(?=(\s|$))", '', line)
# "aaa farmer blooper mouse'd would've bbb"
正则表达式说明
正则表达式的另一种选择是使用否定前瞻来断言re.sub(r"'s?(?!\\S)", '', line)
不是任何非空白字符re.sub(r"'s?(?!\\S)", '', line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.