2016-09-17 35 views
2

使用Python 3,一個簡單的腳本像下面應該運行如預期,但似乎窒息的Unicode表情字符串:Python 3的正則表達式和Unicode表情

import re 

phrase = "(╯°□°)╯ ︵ ┻━┻" 
pattern = r'\b{0}\b'.format(phrase) 

text = "The quick brown fox got tired of jumping over dogs and flipped a table: (╯°□°)╯ ︵ ┻━┻" 

if re.search(pattern, text, re.IGNORECASE) != None: 
    print("Matched!") 

如果我代替單詞「狐狸」爲短語變量的內容,模式確實匹配。我一直困惑,爲什麼它不喜歡這個特定的字符串,而我的手冊和堆棧溢出遠征沒有解決問題。據我所知,Python 3應該沒有問題地處理這個問題。

我錯過了一些痛苦明顯的東西嗎?

編輯:此外,刪除邊界(\ b)不影響匹配字符串的能力。

回答

2
(╯°□°)╯ ︵ ┻━┻ 

這個表達式中有括號,你需要轉義它們。否則,他們被解釋爲組。

In [24]: re.search(r'\(╯°□°\)╯ ︵ ┻━┻', text, re.IGNORECASE) 
Out[24]: <_sre.SRE_Match object; span=(72, 85), match='(╯°□°)╯ ︵ ┻━┻'> 

In [25]: re.findall(r'\(╯°□°\)╯ ︵ ┻━┻', text, re.IGNORECASE) 
Out[25]: ['(╯°□°)╯ ︵ ┻━┻'] 

Escape the regex string正確,你的代碼更改爲:

import re 

phrase = "(╯°□°)╯ ︵ ┻━┻" 
pattern = re.escape(phrase) 

text = "The quick brown fox got tired of jumping over dogs and flipped a table: (╯°□°)╯ ︵ ┻━┻" 

if re.search(pattern, text, re.IGNORECASE) != None: 
    print("Matched!") 

,然後它會如預期:

$ python3 a.py 
Matched! 
+0

這將做到這一點笑。當你盯着一個問題足夠長時,你會怎麼看不見那些顯而易見的東西,這真是太神奇了。儘管如此,我還是需要單詞界限,對於我的具體情況,這似乎也會造成問題。 (目標是在匹配配置文件中的短語時避免Scunthorpe問題的變化,否則我只會使用「如果字符串在字符串中」) –

+0

您能否以確切的要求打開一個新問題? 「我需要」字邊界「是什麼意思? –

+0

這是同樣的問題。假設「短語」沒有硬編碼,刪除周圍的\ b引入了Scunthorpe問題。 –