在 Python 2 窄版本中,非 BMP 字符是两个代理代码点,因此您无法在[]
语法中正确使用它们。 u'[]
等同于u'[\ud83d\udc4d]'
,表示“匹配或之一 。Python 2.7 示例:\ud83d
\udc4d
>>> u'\U0001f44d' == u'\ud83d\udc4d' == u''
True
>>> re.findall(u'[]',u'')
[u'\ud83d', u'\udc4d']
要在 Python 2 和 3 中修复,请匹配u'
OR [+-]
。这将在 Python 2 和 3 中返回正确的结果:
#coding:utf8
from __future__ import print_function
import re
# Note the 'ur' syntax is an error in Python 3, so properly
# escape backslashes in the regex if needed. In this case,
# the backslash was unnecessary.
reg = u"((?P<initial>|[+-])(?P<rest>.+?))$"
tests = u'hello',u'-hello',u'+hello',u'\\hello'
for test in tests:
m = re.match(reg,test)
if m:
print(test,m.groups())
else:
print(test,m)
输出(Python 2.7):
hello (u'\U0001f44dhello', u'\U0001f44d', u'hello')
-hello (u'-hello', u'-', u'hello')
+hello (u'+hello', u'+', u'hello')
\hello None
输出(Python 3.6):
hello ('hello', '', 'hello')
-hello ('-hello', '-', 'hello')
+hello ('+hello', '+', 'hello')
\hello None