我有一个看起来像这样的字符串:
line = "aaa farmer's blooper's mouse'd would've bbb"
从我的字符串,行,如果一个单词以撇号或撇号+ s(' s)结尾,那么我想要删除撇号和s。但我希望保持这个词不变。
所以,我想要我的字符串,
line = "aaa farmer blooper mouse'd would've bbb"
如何使用正则表达式完成此操作?
答案 0 :(得分:3)
使用正则表达式lookahead断言撇号后面的内容,或撇号+ s(' s)可以只是空白字符或字符串结尾,换句话说,单词结尾或字符串结尾
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)