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

请教 Python 正则替换字符串正确成功的姿势?

  •  
  •   uti6770werty · Feb 11, 2020 · 2935 views
    This topic created in 2426 days ago, the information mentioned may be changed or developed.
    [17:31:27]
    

    时间字符,想替换成用"$"符号包裹起来
    像这样:

    $[17:31:27]$
    

    用

    TimeStr = "[17:31:27]"
    TimeStr = re.sub(r"\[\d+:\d+:\d+\]",r"$\1$",TimeStr )
    

    TtimeStr 出来是个空白的字符。。。

    5 replies  •  2020-02-13 14:38:18 +08:00
    gwy15
        1
    gwy15  
       Feb 11, 2020
    ```
    re.sub(r"(\[\d+:\d+:\d+\])",r"$\1$", s)
    ```
    ipwx
        2
    ipwx  
       Feb 11, 2020
    你都没有 group[1],你这句话是怎么执行成功的。。。3.6 直接报错。

    re.sub(r"(\[\d+:\d+:\d+\])",r"$\1$", "[17:31:27]")
    uti6770werty
        3
    uti6770werty  
    OP
       Feb 11, 2020
    @gwy15 成了,谢谢~
    @ipwx 抱歉,我发帖的时候改回了 r",我在测试的时候用的是 u"...[机械狗头]
    ps1aniuge
        4
    ps1aniuge  
       Feb 12, 2020   ❤️ 1
    “[”替换成"$[",不就完了么?
    deplives
        5
    deplives  
       Feb 13, 2020
    同楼上,如果格式固定,直接 replace("[","$[") replace("]","]$") 不比正则好使
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2427 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 13:46 · PVG 21:46 · LAX 06:46 · JFK 09:46
    ♥ Do have faith in what you're doing.