V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
uti6770werty
V2EX  ›  问与答

Python 的 re.sub 正则替换问题

  •  
  •   uti6770werty · 2020-05-21 22:36:38 +08:00 · 954 次点击
    这是一个创建于 1450 天前的主题,其中的信息可能已经有所发展或是发生改变。
    stringa = "苹果 32 公斤"
    TextDict['apple'] = re.sub(r"\d+公斤",r"[\d+]公斤",stringa)
    理论上 TextDict['apple']应该是"苹果[32]公斤"
    发现结果不是,是 sub 的语句错了么?
    4 条回复    2020-05-21 23:19:55 +08:00
    imn1
        1
    imn1  
       2020-05-21 22:38:54 +08:00
    re.sub(r"(\d+)公斤",r"[$1]公斤",stringa)
    inhzus
        2
    inhzus  
       2020-05-21 22:40:59 +08:00
    ```
    re.sub(r"(\d+)公斤", r"[\1]公斤", stringa)
    ```

    建议重读文档: https://docs.python.org/3/library/re.html#re.sub
    imn1
        3
    imn1  
       2020-05-21 22:44:15 +08:00
    nnd,老是忘了 py 用 \,不用$
    #2 正确,#1 写错了
    vmebeh
        4
    vmebeh  
       2020-05-21 23:19:55 +08:00 via iPhone
    是想给数字加括号?
    中括号要转义
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1127 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:42 · PVG 02:42 · LAX 11:42 · JFK 14:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.