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

请问正则表达式如何排除一个特定的单词?

  •  
  •   dwjgwsm · 2018-04-17 11:04:59 +08:00 · 6087 次点击
    这是一个创建于 2172 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 中

    data = r'test TES(1+2) MAX(3+2) AX(4+5)'

    x=r'([^()]*)'

    x=r'[A-Z]+' + x

    b=re.findall(x,data)

    print(b)

    要求输出 ['TES(1+2)','AX(4+5)']

    排除掉前缀为 MAX 的字符串,我尝试前面加(?!MAX) 但不成功

    4 条回复    2018-04-17 11:28:34 +08:00
    xiangyuecn
        1
    xiangyuecn  
       2018-04-17 11:14:52 +08:00
    来一发正则表达式

    \b(?!max)\w+?\(.+?\)
    dwjgwsm
        2
    dwjgwsm  
    OP
       2018-04-17 11:23:06 +08:00
    @xiangyuecn 谢谢~!也可以这么写:
    x=r'\([^()]*\)'

    x=r'\b(?!MAX)[A-Z]+?' + x
    LadyChunsKite
        3
    LadyChunsKite  
       2018-04-17 11:26:42 +08:00
    酱紫也行:[A-Z]+(?<!MAX)\(.*?\)
    Hopetree
        4
    Hopetree  
       2018-04-17 11:28:34 +08:00
    \s((?!MAX)[A-Z]+?\(.+?\))

    \s 表示大写字母前面的空格,(?!MAX)表示不匹配这个,[A-Z]+?表示匹配大写字母,\(.+?\)括号和里面的内容
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3238 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:55 · PVG 21:55 · LAX 06:55 · JFK 09:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.