V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
frmongo
V2EX  ›  Python

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

  •  
  •   frmongo · 2018-08-06 18:19:45 +08:00 · 2157 次点击
    这是一个创建于 2091 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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)
    
    6 条回复    2018-08-06 18:31:20 +08:00
    as4069825
        1
    as4069825  
       2018-08-06 18:22:57 +08:00
    是不是括号包括号的问题
    ranleng
        2
    ranleng  
       2018-08-06 18:23:40 +08:00
    空格....
    ranleng
        3
    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
        4
    frmongo  
    OP
       2018-08-06 18:27:05 +08:00
    @ranleng 我编辑的问题,字符串中原来应该没有空格,我仔细看了下,你好像没修改什么....
    frmongo
        5
    frmongo  
    OP
       2018-08-06 18:29:17 +08:00
    哦,你是加了空格,其实原来的字符串没空格 timestr= u"2018 年 3 月 28 日"
    frmongo
        6
    frmongo  
    OP
       2018-08-06 18:31:20 +08:00
    我擦,我发现报错的原因是使用了 VScode, 使用 cmd 调用 cpytohn 就可以了....
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5341 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:11 · PVG 15:11 · LAX 00:11 · JFK 03:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.