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
plko345
V2EX  ›  Python

请教一个 re 正则的问题

  •  
  •   plko345 · 2021-05-09 12:37:32 +08:00 · 1935 次点击
    这是一个创建于 1054 天前的主题,其中的信息可能已经有所发展或是发生改变。

    匹配 数字三连....

    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 条回复    2021-05-10 09:24:46 +08:00
    oldshensheep
        1
    oldshensheep  
       2021-05-09 12:44:23 +08:00
    Trim21
        2
    Trim21  
       2021-05-09 12:47:21 +08:00 via Android
    试了试第二个能正确匹配
    cherbim
        3
    cherbim  
       2021-05-09 13:06:38 +08:00 via iPhone
    我测试第二个成功啊
    ClericPy
        4
    ClericPy  
       2021-05-09 13:52:37 +08:00
    python 3.7 3.8 3.9 2.7 都能正确匹配

    要不你试试 r'\d{3}'
    iptables
        5
    iptables  
       2021-05-09 13:56:46 +08:00
    我的测试结果

    $ 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
        6
    plko345  
    OP
       2021-05-09 14:00:57 +08:00
    @Trim21
    @cherbim
    @ClericPy
    @iptables

    谢谢各位, 尴尬了, 我再找找是不是我哪里搞错了
    crystom
        7
    crystom  
       2021-05-09 14:25:21 +08:00   ❤️ 3
    python3 的\d 包括各种 unicode 数字,不光是 0-9
    imn1
        8
    imn1  
       2021-05-09 15:05:31 +08:00
    @crystom #7
    哇靠,还真不知这个,测试了一下,全角数字也能匹配,不会罗马数字也行吧?
    yunyuyuan
        9
    yunyuyuan  
       2021-05-10 09:24:46 +08:00
    @crystom 涨见识了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3089 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 12:51 · PVG 20:51 · LAX 05:51 · JFK 08:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.