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

一个关于正则表达式的问题,两个固定字符串之间的字符提取

  •  
  •   j0shfan · 2021-01-05 14:24:31 +08:00 · 1529 次点击
    这是一个创建于 1207 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请问大家,如何表达提取在两个已知字符之间的字符(不包含那两个已知字符) 比方现在有一个字符串 20:19:48.654 : Reply[2] from 172.16.178.125: bytes=256 time=5.2 ms TTL=62 jitter=0.10 ms 我想提取的是 Reply[2]中的 2 那么现在我的方法是先将 [ 2 ] 提取出来,使用'[\d]' 再将 2 使用'\d'提取出来

    能不能直接定义取出'Reply['和']'之间的数字 谢谢大家,我发现我这句语法的不懂,给我造成了很多麻烦

    5 条回复    2021-01-05 15:22:41 +08:00
    morevin
        1
    morevin  
       2021-01-05 14:41:20 +08:00
    re.findall('Reply\[([0-9]*)]', 目标字符串)[0]
    ymcz852
        2
    ymcz852  
       2021-01-05 14:41:25 +08:00
    'Reply[2] from'.match(/Reply\[(\d+)\]/)
    可以使用捕获括号去分组匹配
    jifengg
        3
    jifengg  
       2021-01-05 15:00:49 +08:00
    \[([\d]+)\]

    直接取出,就用()分组,然后直接取捕获到的内容。
    xdnauly
        4
    xdnauly  
       2021-01-05 15:02:11 +08:00
    In [30]: import re

    In [31]: re.sub(".*Reply\[(\d+)\].*", r"\1", "20:19:48.654 : Reply[2] from 172.16.178.125: bytes=256 time=5.2 ms TTL=62 jitter=0.10 ms")
    Out[31]: '2'

    ###########
    #答案
    re.sub(".*Reply\[(\d+)\].*", r"\1", target_str)
    jswh
        5
    jswh  
       2021-01-05 15:22:41 +08:00   ❤️ 1
    1.用括号分组
    2.用零宽断言

    另推荐教程 https://deerchao.cn/tutorials/regex/regex.htm#lookaround
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5672 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 06:29 · PVG 14:29 · LAX 23:29 · JFK 02:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.