![](/img/trans.png)
[英]How to get rid of words with special characters in Python using regular expressions?
[英]How can Python's regular expressions work with patterns that have escaped special characters?
有沒有辦法讓Python的正則表達式與已轉義特殊字符的模式一起使用? 就我有限的理解所知,下面的示例應該可以工作,但是該模式無法匹配。
import re
string = r'This a string with ^g\.$s' # A string to search
pattern = r'^g\.$s' # The pattern to use
string = re.escape(string) # Escape special characters
pattern = re.escape(pattern)
print(re.search(pattern, string)) # This prints "None"
注意:
是的,已經在其他地方(例如這里 )問過這個問題。 但是正如您所看到的,我已經在實施答案中描述的解決方案,但仍無法正常工作。
為什么在地球上您要對string
應用re.escape
? 您想在其中找到“特殊”字符! 如果僅將其應用於pattern
,則將獲得一個匹配項:
>>> import re
>>> string = r'This a string with ^g\.$s'
>>> pattern = r'^g\.$s'
>>> re.search(re.escape(pattern), re.escape(string)) # nope
>>> re.search(re.escape(pattern), string) # yep
<_sre.SRE_Match object at 0x025089F8>
為了獲得加分,請注意,您只需要比string
多re.escape
一次re.escape
pattern
:
>>> re.search(re.escape(re.escape(pattern)), re.escape(string))
<_sre.SRE_Match object at 0x025D8DE8>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.