python regex不以某些字符结尾

2024-05-23 18:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望下面的代码:

content ="'Yoda' :"
content = re.sub("\w\s*'\s*[^:]", "", content)
print content

打印输出:'Yoda':但它打印了'Yod: 我的意图是:如果字符串不以:结尾,则用空字符串替换;如果以:结尾,则不执行任何操作。但上面的regex仍然取代了它。请问如何修改正则表达式。提前谢谢。在


Tags: 字符串代码re结尾content意图regexprint
1条回答
网友
1楼 · 发布于 2024-05-23 18:31:35

您需要在正则表达式的末尾使用锚定符$,它指定字符串的结尾。在

>>> content ="'Yoda' :"
>>> content = re.sub("\w\s*'\s*[^:]$", "", content)
>>> print (content)
'Yoda' :

但是您可以不使用regex,只需使用str.endswith()来完成此任务:

^{pr2}$

相关问题 更多 >