[英]Remove apostrophe from string Python regex
I have the following string: 我有以下字符串:
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'
How do I use a regex to remove all apostrophe that is between words? 如何使用正则表达式删除单词之间的所有撇号? I tried using
re.sub('(?<=[az])'(?=[az])', '', s)
but cannot get the desired result. 我尝试使用
re.sub('(?<=[az])'(?=[az])', '', s)
但无法获得所需的结果。
You need to escape the single quote in your regex to distinguish it from the pattern which is also in single quotes: 您需要在正则表达式中转义单引号,以使其与也在单引号中的模式区分开:
re.sub('(?<=[a-z])\'(?=[a-z])', '', s)
But, another solution would be to just use double quotes for the entire pattern: 但是,另一种解决方案是仅对整个模式使用双引号:
re.sub("(?<=[a-z])'(?=[a-z])", "", s)
If it's not set in stone that you have to use regex; 如果不是一成不变,则必须使用正则表达式;
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("'", ""))
OUTPUT: 输出:
>>> 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
Regarding Kevin's comment, using the count
of the occurrences less 1; 对于凯文的评论,使用
count
的出现少1;
print(sentence.replace("'", "", sentence.count("'")-1))
OUTPUT: 输出:
>>> 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.