PYTHON RE在匹配时不要将UNICODE字符分成代理对

时间:2018-08-17 00:04:22

标签: python regex unicode surrogate-pairs

谁知道,在将代码点拆分为代理对时是否有可能禁止正则表达式。

请参见以下示例:

现在如何:

$ te = u'\U0001f600\U0001f600'
$ flags1 = regex.findall(".", te, re.UNICODE)
$ flags1
>>> [u'\ud83d', u'\ude00', u'\ud83d', u'\ude00']

我的愿望:

$ te = u'\U0001f600\U0001f600'
$ flags1 = regex.findall(".", te, re.UNICODE)
$ flags1
>>> [u'\U0001f600', u'\U0001f600']

我为什么真正需要它,因为我想遍历unicode字符串并获得每次迭代的下一个unicode字符。

查看示例:

for char in  regex.findall(".", te, re.UNICODE):
   print char

预先感谢您)

1 个答案:

答案 0 :(得分:0)

使用与代理对或任何其他匹配的正则表达式。这将在Python 2的广泛和狭窄版本中工作,但由于它不使用代理对,因此在广泛版本中不需要。

Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> te = u'A\u5200\U0001f600\U0001f601\u5100Z'
>>> print re.findall(ur'[\ud800-\udbff][\udc00-\udfff]|.', te, re.UNICODE)
[u'A', u'\u5200', u'\U0001f600', u'\U0001f601', u'\u5100', u'Z']

这在最新的Python 3中仍然可以使用,但是也不需要,因为在Unicode字符串中不再使用代理对(不再有宽或窄的构造):

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> te = u'A\u5200\U0001f600\U0001f601\u5100Z'
>>> print(re.findall(r'[\ud800-\udbff][\udc00-\udfff]|.', te))
['A', '刀', '', '', '儀', 'Z']

没有替代匹配的作品:

>>> print(re.findall(r'.', te))
['A', '刀', '', '', '儀', 'Z']

然后您可以在Python 3中正常进行迭代:

>>> for c in te:
...     print(c)
...
A
刀


儀
Z

请注意, graphemes (代表单个字符的Unicode代码点组合)仍然存在问题。这是一个糟糕的情况:

>>> s = '‍‍‍'
>>> for c in s:
...     print(c)
...     


‍


‍


‍


regex第三方模块可以匹配字素:

>>> import regex
>>> s = '‍‍‍'
>>> for c in regex.findall('\X',s):
...     print(c)
...     
‍‍‍