Python3正则表达式和Unicode表情

2024-05-12 17:18:51 发布

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

使用Python3,下面这样一个简单的脚本应该按预期运行,但似乎被unicode emote字符串阻塞了:

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”代替短语变量的内容,那么模式确实匹配。我一直困惑于为什么它不喜欢这个特殊的字符串,而我对手册和堆栈溢出的探索并没有阐明这个问题。据我所知,python3应该可以毫无问题地处理这个问题。你知道吗

我是不是错过了一些显而易见的东西?你知道吗

编辑:同样,删除边界(\b)也不会影响匹配字符串的能力。你知道吗


Tags: the字符串textimportre脚本formatunicode
1条回答
网友
1楼 · 发布于 2024-05-12 17:18:51
(╯°□°)╯ ︵ ┻━┻

这个表达式中有括号,您需要对其进行转义。否则,它们被解释为组。你知道吗

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!

相关问题 更多 >