python 3找到一个未跟随子字符串的字符串

时间:2017-11-30 02:51:04

标签: python regex python-3.x

我有一个看起来像这样的字符串:

line = "aaa farmer's blooper's mouse'd would've bbb"

从我的字符串,行,如果一个单词以撇号或撇号+ s(' s)结尾,那么我想要删除撇号和s。但我希望保持这个词不变。

所以,我想要我的字符串,

line = "aaa farmer blooper mouse'd would've bbb"

如何使用正则表达式完成此操作?

1 个答案:

答案 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"

正则表达式解释

  • ' S? #mattatrophe跟随零或一个
  • (?=(\ s | $))#断言什么 跟随可以只是空格字符或字符串结尾

正则表达式的另一个替代方案是使用否定前瞻来断言后面跟不是任何非空白字符 re.sub(r"'s?(?!\S)", '', line)