从字符串Python的正则表达式删除撇号

时间:2019-01-28 13:56:24

标签: python regex

我有以下字符串:

i've been running from what i don't know if she's there or if she's cares it's taken you a long time to see you've got a goldfish memory this song's ed'

我如何使用正则表达式来删除所有撇号是词与词之间?我尝试使用re.sub('(?<=[a-z])'(?=[a-z])', '', s),但无法获得理想的结果。

2 个答案:

答案 0 :(得分:5)

您需要在正则表达式中转义单引号,以将其与也在单引号中的模式区分开来

re.sub('(?<=[a-z])\'(?=[a-z])', '', s)

但是,另一种解决方案是仅对整个模式使用双引号:

re.sub("(?<=[a-z])'(?=[a-z])", "", s)

答案 1 :(得分:2)

如果不是一成不变的,就必须使用正则表达式;

sentence = r"i've been running from what i don't know if she's there or if she's cares it's taken you a long time to see you've got a goldfish memory this song's ed'"

print(sentence.replace("'", ""))

输出:

>>> ive been running from what i dont know if shes there or if shes cares its taken you a long time to see youve got a goldfish memory this songs ed

关于凯文的评论,使用事件中的count减去1;

print(sentence.replace("'", "", sentence.count("'")-1))

输出:

>>> ive been running from what i dont know if shes there or if shes cares its taken you a long time to see youve got a goldfish memory this songs ed'