推荐学习书目
› 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
plko345
V2EX  ›  Python

请教一个 re 正则的问题

  •  
  •   plko345 · May 9, 2021 · 3100 views
    This topic created in 2007 days ago, the information mentioned may be changed or developed.

    匹配 数字三连....

    import re
    
    s = 'abc 456 def'
    
    re.search('\d\d\d', s)       # 成功
    re.search('\d{3}', s)        # None
    re.search('[0-9]{3}', s)    # 成功
    

    为什么 \d{3} 不行, 我在在线正则测试的工具网站上试过 \d{3} 并没有错, google 也没找到有说明的, 可能是关键字不对

    9 replies  •  2021-05-10 09:24:46 +08:00
    Trim21
    Trim21
    May 9, 2021 via Android
    2
    试了试第二个能正确匹配
    cherbim
    cherbim
    May 9, 2021 via iPhone
    3
    我测试第二个成功啊
    ClericPy
    ClericPy
    May 9, 2021
    4
    python 3.7 3.8 3.9 2.7 都能正确匹配

    要不你试试 r'\d{3}'
    iptables
    iptables
    May 9, 2021
    5
    我的测试结果

    $ python3.9
    Python 3.9.5 (default, May 3 2021, 19:12:05)
    [Clang 12.0.5 (clang-1205.0.22.9)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import re
    >>>
    >>> s = 'abc 456 def'
    >>>
    >>> re.search('\d\d\d', s)
    <re.Match object; span=(4, 7), match='456'>
    >>> re.search('\d{3}', s)
    <re.Match object; span=(4, 7), match='456'>
    >>> re.search('[0-9]{3}', s)
    <re.Match object; span=(4, 7), match='456'>
    >>>
    >>> re.search(r'\d\d\d', s)
    <re.Match object; span=(4, 7), match='456'>
    >>> re.search(r'\d{3}', s)
    <re.Match object; span=(4, 7), match='456'>
    >>> re.search(r'[0-9]{3}', s)
    <re.Match object; span=(4, 7), match='456'>
    >>>
    plko345
    plko345
    OP
    May 9, 2021
    6
    @Trim21
    @cherbim
    @ClericPy
    @iptables

    谢谢各位, 尴尬了, 我再找找是不是我哪里搞错了
    crystom
    crystom
    May 9, 2021❤️3
    7
    python3 的\d 包括各种 unicode 数字,不光是 0-9
    imn1
    imn1
    May 9, 2021
    8
    @crystom #7
    哇靠,还真不知这个,测试了一下,全角数字也能匹配,不会罗马数字也行吧?
    yunyuyuan
    yunyuyuan
    May 10, 2021
    9
    @crystom 涨见识了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1864 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 01:34 · PVG 09:34 · LAX 17:34 · JFK 20:34
    ♥ Do have faith in what you're doing.