【问题标题】:Remove brackets around text and add colon at the end删除文本周围的括号并在末尾添加冒号
【发布时间】:2018-05-24 15:34:46
【问题描述】:

我有一个很长的字符串,并且想替换出现的这种情况:

'eggs (spam): tomatoes'

与这种类型的:

'eggs : spam tomatoes'

也就是说,如果有'左括号,文本,右括号,双冒号,空格'这样的模式,那么我希望将它替换为'双冒号,空格,文本' .

我已尝试编写以下内容:

import re
re.sub('\(.+\): ', '', 'eggs (spam): tomatoes')

但是(不出所料)它完全删除了括号中的文本,我不知道如何保留之前在函数的“替换”部分中括号中的文本。

【问题讨论】:

    标签: python regex text


    【解决方案1】:

    您应该使用捕获组:

    re.sub(r"\(([^()]*)\)(:)", r"\2 \1", 'eggs (spam): tomatoes')
    

    Live demo

    正则表达式分解:

    • \(匹配左括号
    • ( 第一组抓包开始
      • [^()]*匹配之间的任何东西
    • )第一组捕获结束
    • \) 匹配右括号
    • (:) 捕获冒号(CG #2)

    替换字符串"\2 \1" 表示替换应跟随第二个捕获组数据,然后是空格,然后首先捕获组数据。

    【讨论】:

    • 我刚刚尝试运行它并得到了这个输出'eggs $2 $1 tomatoes'
    【解决方案2】:

    使用re.sub('\((.*?)\): ', r':\1 ', 'eggs (spam): tomatoes')

    演示:

    import re
    print(re.sub('\((.*?)\): ', r':\1 ', 'eggs (spam): tomatoes'))
    

    输出:

    eggs :spam tomatoes
    

    【讨论】:

      【解决方案3】:

      这行得通:

      >>> re.sub('\((.*)\): ', ': \\1 ', 'eggs (spam): tomatoes')
      eggs : spam tomatoes
      

      【讨论】:

        【解决方案4】:

        您可以使用re.findallre.sub

        import re
        s = 'eggs (spam): tomatoes'
        new_s = re.sub('\(\w+\):', '{}', s).format(*[f': {i}' for i in re.findall('\((.*?)\)', s)])
        

        输出:

        'eggs : spam tomatoes'
        

        【讨论】:

          【解决方案5】:

          在您的代码中,您从左括号中选择直到包括冒号在内的右括号,并将其替换为空字符串。这就是它完全删除括号中的文本的原因。

          您可以使用 2 个捕获组并替换为第 2 组第 1 组:

          \((.+?)\)(:)

          • \( 字面匹配
          • (.+?) 在第 1 组中捕获 \\1 任意字符一次或多次非贪婪
          • \) 字面匹配
          • (:) 捕获第 2 组中的冒号 \\2

          例如:

          import re
          print(re.sub(r"\((.+?)\)(:)", "\\2 \\1", 'eggs (spam): tomatoes'))
          

          这会给你:

          eggs : spam tomatoes
          

          Demo

          【讨论】:

            猜你喜欢
            • 2020-08-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-05-28
            • 1970-01-01
            • 1970-01-01
            • 2013-03-20
            • 2020-02-24
            相关资源
            最近更新 更多