![](/img/trans.png)
[英]Python RegEx: How to conditionally match multiple optional ending characters in a URL
[英]python regex not ending with some characters
嗨希望以下代碼:
content ="'Yoda' :"
content = re.sub("\w\s*'\s*[^:]", "", content)
print content
打印出來: 'Yoda':但它打印出'Yod:我的意圖是:如果字符串沒有結束:然后用空字符串替換它,如果結束於:則不執行任何操作。 但上面的正則表達式仍然取而代之。 我該如何修改正則表達式呢。 提前致謝。
你需要在正則表達式末尾的錨$
,指定字符串的結尾。
>>> content ="'Yoda' :"
>>> content = re.sub("\w\s*'\s*[^:]$", "", content)
>>> print (content)
'Yoda' :
但是你可以在沒有正則表達式的情況下執行此任務,只需使用str.endswith()
:
content ="'Yoda' :"
if not content.endswith(':'):
content=''
else:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.