Skip to main content
 首页 » 编程设计

Python 正则表达式匹配 unicode 表情符号

2024年08月30日30fff_TT

我正在尝试构建一个正则表达式来匹配负面 unicode 表情符号的不同可能组合。我在匹配下面列表 test_2 中包含的表情符号类型时遇到问题。虽然我相信符合表情符号的非字母数字符号已正确放置在正则表达式中,但表情符号和左眼(捕获的名为 eye1 的组)都不匹配......我该如何解决?谢谢

neg_emoticon_regular = ur""" 
  [\((]?     #optional left parenthesis 
  \s*         #optional space    
  [\`\#\ ́]?   #optional symbols between left parenthesis and left eye 
  (?P<eye1>[\ー\; \́\`\・\>Tt\ー\ ̄\−\-\゚~\_\.\>\*\/]) #left eye 
  \s*         #optional space                      
  [\。\。\Δ\-\人\O\0\.\Д\д\o\−\_\ω\ヘ\^\_]? #mouth 
  \s*         #optional space   
  [(?P=eye1)\`\<\’]   #right eye, usually will match left eye                 
  [\A\#\;]?   #optional symbols between right eye and right parenthesis 
  \s*         #optional space 
  [\)\)]?    #optional right parenthesis    
""" 
 
neg_emoticon_re = re.compile(neg_emoticon_regular, re.VERBOSE  | re.UNICODE) 
test_2 = ["(−_−#)","(-。-;","(-_-)"] #negative emoticons to match 
for e in test_2: 
    e_uc_norm = unicodedata.normalize('NFKC', e.decode("utf-8")) 
    m = neg_emoticon_re.search(e_uc_norm)  
    if m: print "eye1:",m.group("eye1") #print the symbol that is supposed to be the left eye 
    print len(neg_emoticon_re.findall(e_uc_norm)), e_uc_norm 

请您参考如下方法:

在正则表达式中,[...] 是一组字符,因此 [\(() 将匹配左括号或空格(它可以缩短为 [( ]),而 [\s+]? 将匹配可选的空白字符或加号。