V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
uti6770werty
V2EX  ›  问与答

Python 的 re.sub 正则替换问题

  •  
  •   uti6770werty · May 21, 2020 · 1288 views
    This topic created in 2180 days ago, the information mentioned may be changed or developed.
    stringa = "苹果 32 公斤"
    TextDict['apple'] = re.sub(r"\d+公斤",r"[\d+]公斤",stringa)
    理论上 TextDict['apple']应该是"苹果[32]公斤"
    发现结果不是,是 sub 的语句错了么?
    4 replies    2020-05-21 23:19:55 +08:00
    imn1
        1
    imn1  
       May 21, 2020
    re.sub(r"(\d+)公斤",r"[$1]公斤",stringa)
    inhzus
        2
    inhzus  
       May 21, 2020
    ```
    re.sub(r"(\d+)公斤", r"[\1]公斤", stringa)
    ```

    建议重读文档: https://docs.python.org/3/library/re.html#re.sub
    imn1
        3
    imn1  
       May 21, 2020
    nnd,老是忘了 py 用 \,不用$
    #2 正确,#1 写错了
    vmebeh
        4
    vmebeh  
       May 21, 2020 via iPhone
    是想给数字加括号?
    中括号要转义
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1239 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 17:28 · PVG 01:28 · LAX 10:28 · JFK 13:28
    ♥ Do have faith in what you're doing.