Skip to main content
 首页 » 编程设计

Python 3 正则表达式和 Unicode 表情

2024年10月17日33zlslch

使用 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!") 

如果我用单词“fox”代替短语变量的内容,模式确实匹配。我一直对为什么它不喜欢这个特定的字符串感到困惑,而且我对手册和 Stack Overflow 的探索并没有阐明这个问题。据我所知,Python 3 应该可以毫无问题地处理这个问题。

我是不是漏掉了一些明显的东西?

编辑:此外,删除边界 (\b) 也不会影响匹配字符串的能力。

请您参考如下方法:

(╯°□°)╯ ︵ ┻━┻ 

这个表达式里面有括号,你需要转义它们。否则,它们将被解释为组。

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!