问个正则表达式中的中文的问题?

2018-08-06 18:19:45 +08:00
 frmongo

1. 说明

我本来是想匹配时间的,无意中发现包含中文的字符串,总体的匹配无法输出,就是 print m.group(0)和 print m.group(1)会报错,这是为什么呢?

2. CODE

# coding=utf-8
timestr= u"2018 年 3 月 28 日"
m = re.match(u"((\d+)年(\d+)月(\d+)日)", timestr)
print m.group(0)
print m.group(1)
print m.group(2)
print m.group(3)
2173 次点击
所在节点    Python
6 条回复
as4069825
2018-08-06 18:22:57 +08:00
是不是括号包括号的问题
ranleng
2018-08-06 18:23:40 +08:00
空格....
ranleng
2018-08-06 18:25:01 +08:00
手滑直接回复了.

按照你的正则 m 是 None
>>> m.group
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
改成 m=re.match(u"((\d+) 年 (\d+) 月 (\d+) 日)", timestr)
就没有问题
frmongo
2018-08-06 18:27:05 +08:00
@ranleng 我编辑的问题,字符串中原来应该没有空格,我仔细看了下,你好像没修改什么....
frmongo
2018-08-06 18:29:17 +08:00
哦,你是加了空格,其实原来的字符串没空格 timestr= u"2018 年 3 月 28 日"
frmongo
2018-08-06 18:31:20 +08:00
我擦,我发现报错的原因是使用了 VScode, 使用 cmd 调用 cpytohn 就可以了....

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/477364

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX