推荐学习书目
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 · Aug 6, 2018 · 3038 views
    This topic created in 2836 days ago, the information mentioned may be changed or developed.

    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 replies    2018-08-06 18:31:20 +08:00
    as4069825
        1
    as4069825  
       Aug 6, 2018
    是不是括号包括号的问题
    ranleng
        2
    ranleng  
       Aug 6, 2018
    空格....
    ranleng
        3
    ranleng  
       Aug 6, 2018
    手滑直接回复了.

    按照你的正则 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
       Aug 6, 2018
    @ranleng 我编辑的问题,字符串中原来应该没有空格,我仔细看了下,你好像没修改什么....
    frmongo
        5
    frmongo  
    OP
       Aug 6, 2018
    哦,你是加了空格,其实原来的字符串没空格 timestr= u"2018 年 3 月 28 日"
    frmongo
        6
    frmongo  
    OP
       Aug 6, 2018
    我擦,我发现报错的原因是使用了 VScode, 使用 cmd 调用 cpytohn 就可以了....
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4509 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 10:07 · PVG 18:07 · LAX 03:07 · JFK 06:07
    ♥ Do have faith in what you're doing.