如何在 python 2.7 中使用 re.UNICODE? [英] How do I use re.UNICODE in python 2.7?

查看:69
本文介绍了如何在 python 2.7 中使用 re.UNICODE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 re.UNICODE 标志来匹配可能包含 unicode 字符的字符串,但它似乎不起作用.例如:

Python 2.7.12(默认,2017 年 12 月 4 日,14:50:18)[GCC 5.4.0 20160609] 在 linux2输入帮助"、版权"、信用"或许可"以获取更多信息.>>>进口重新>>>r = re.compile(ur"(\w+)", re.UNICODE)>>>r.findall(u"test test test", re.UNICODE)[]

如果我不指定 unicode 标志它可以工作,但显然它不适用于 unicode 字符串.我需要做什么才能使其正常工作?

解决方案

r.findall 的第二个参数不是标志,而是 pos.如果您已经在 compile 中指定了标志,则无需再次指定标志.

<预><代码>>>>r = re.compile(ur"(\w+)", re.UNICODE)>>>r.findall(u'test test test')[你'测试',你'测试',你'测试']

I am trying to use the re.UNICODE flag to match a string potentially containing unicode characters, but it doesn't seem to be working. E.g.:

Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> r = re.compile(ur"(\w+)", re.UNICODE)
>>> r.findall(u"test test test", re.UNICODE)
[]

It works if I do not specify the unicode flag, but then obviously it will not work with unicode strings. What do I need to do to get this working?

解决方案

The second argument to r.findall is not flags, but pos. You don't need to specify flags again when you already specified them in compile.

>>> r = re.compile(ur"(\w+)", re.UNICODE)
>>> r.findall(u'test test test')
[u'test', u'test', u'test']

这篇关于如何在 python 2.7 中使用 re.UNICODE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆