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

帮我看下这个正则表达式

  •  
  •   fan2006 · Dec 28, 2018 · 2905 views
    This topic created in 2718 days ago, the information mentioned may be changed or developed.
    下面这个正则:
    re.findall(r'(?<!数量)\d+','数量 123 单价 45 金额 5535')
    得到了结果:
    ['23', '45', '5535']
    我想以否定的模式来写,就是不想提取数量后面的数值,在结果的 list 里面数量那个 23 不应该出现的。
    10 replies    2019-01-04 13:33:12 +08:00
    fan2006
        1
    fan2006  
    OP
       Dec 28, 2018
    自己研究写了一个出来。python 3
    re.findall(r'[一-龥]+(?<!数量)(\d+)','数量 123 单价 45 金额 5535')
    结果:
    ['45', '5535']
    no1xsyzy
        2
    no1xsyzy  
       Dec 28, 2018   ❤️ 1
    因为匹配了 “数量 1 ”
    re.findall(r'(?<!数量)\s(\d+)','数量 123 单价 45 金额 5535')
    fan2006
        3
    fan2006  
    OP
       Dec 28, 2018
    @no1xsyzy 嗯,非常感谢大大
    nekoneko
        4
    nekoneko  
       Dec 28, 2018
    数量和\d 中间加个空格试试
    fan2006
        5
    fan2006  
    OP
       Dec 28, 2018
    @nekoneko 其实字符串之间没有空格,我那个还是能起作用
    nekoneko
        6
    nekoneko  
       Dec 28, 2018
    @fan2006 (?<!数量\d*)\d+
    imn1
        7
    imn1  
       Dec 28, 2018
    空格是 V2 后台加的么?
    python 的 re.findall 总有难以预想的情况
    正常理解,「(?<!数量)\d+」和「(?<!数量)(\d+)」是一样的,似乎 python 里面有优先级的区别
    fan2006
        8
    fan2006  
    OP
       Dec 28, 2018
    @nekoneko 你这个报错。提示 look-behind requires fixed-width pattern
    fan2006
        9
    fan2006  
    OP
       Dec 28, 2018
    @imn1 确实后台加的。。\d+没括号就会捕捉带文字数值,应该是匹配整个 pattern 作为分组,带了括号就会只取得数字匹配括号分组。
    nekoneko
        10
    nekoneko  
       Jan 4, 2019
    @fan2006 编译器的锅好像,不支持不定长度。(?<!数量[0-9]{0,100000})[0-9]+这样就可以了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   898 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 22:24 · PVG 06:24 · LAX 15:24 · JFK 18:24
    ♥ Do have faith in what you're doing.