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

这个正则怎么写啊?

  •  
  •   llsquaer · Oct 31, 2020 · 3461 views
    This topic created in 2020 days ago, the information mentioned may be changed or developed.

    用的 python

    假设有一段文字

    aaa.bbb.ccc.xxx(ddd.fffssss.eeee)
    

    所有字符都是不等长的单词..需要做的是.提取出如下格式内容

    xxx(ddd.fffssss.eeee)
    

    提取出 . 号到 ( 号 和 ()号内 的文字..

    这样的正则怎么写啊????

    9 replies    2020-11-02 11:11:36 +08:00
    gwy15
        1
    gwy15  
       Oct 31, 2020
    \.(\w+\(.+\))
    Fechin
        2
    Fechin  
    PRO
       Oct 31, 2020
    (?<=\.)[^\.]+\([^)]+\)
    llsquaer
        3
    llsquaer  
    OP
       Oct 31, 2020
    @gwy15 十分感谢啊. 为什么把 \w+ 改为 .+ 就变成了从开始位置的 . 开始了呢? 之前一直用 . 代表任意字符....所以之前一直没匹配上..
    natsukage
        4
    natsukage  
       Oct 31, 2020   ❤️ 2
    @llsquaer #3 因为正则表达式引擎在匹配字符串和表达式时,是从前向后逐个扫描字符串中的字符,并判断是否与表达式符合的。 .bbb.ccc.xxx 和 .xxx 虽然都可以匹配 .+,但是正则表达式扫描的时候,从 .bbb 就已经开始能够正常匹配,一直持续到后面的整个 .bbb.ccc.xxx(ddd.fffssss.eeee) 结束匹配完成。虽然.ccc.xxx(ddd.fffssss.eeee)和.xxx(ddd.fffssss.eeee)也能完成匹配,但是因为.bbb.ccc.xxx(ddd.fffssss.eeee)是先来的,所以正则表达式会娶先来的这个作为最终结果。
    如果想要解决这个问题,要么就是想办法让.bbb.ccc.xxx 和.ccc.xxx 不满足匹配,1 楼的解法就是这么做的,通过 \w 取代 . ,这样.xxx 就是第一个满足匹配的前缀了,因此能够正常匹配到你想要的结果。
    要么就是提前把前面的部分( aaa.bbb.ccc.)全部用非捕获组匹配掉,然后在剩下的部分里匹配你想要匹配的内容,例如(?:.+\.)(?<match>.+?\([^)]+\))
    dorothyREN
        5
    dorothyREN  
       Oct 31, 2020
    grep -o "[a-zA-Z]*(.*)"
    dorothyREN
        6
    dorothyREN  
       Oct 31, 2020
    ```
    [root@db ~]# grep -o "[a-zA-Z]*(.*)" a
    xxx(ddd.fffssss.eeee)
    [root@db ~]#
    ```
    dorothyREN
        7
    dorothyREN  
       Oct 31, 2020
    re.search(r"\.[^.]*\(.*\)", a)
    huyangabc
        8
    huyangabc  
       Oct 31, 2020
    \.(\w+\(.*\))
    llsquaer
        9
    llsquaer  
    OP
       Nov 2, 2020
    @natsukage
    @dorothyREN
    谢谢你们俩的解答...通过测试,终于算是搞明白了.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5746 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 03:38 · PVG 11:38 · LAX 20:38 · JFK 23:38
    ♥ Do have faith in what you're doing.