【问题标题】:How can I remove the closing square bracket using regex in Python?如何在 Python 中使用正则表达式删除右方括号?
【发布时间】:2021-07-17 11:06:31
【问题描述】:

我有一个混乱的字符串列表 (list_strings),我可以使用 regex 删除不需要的字符,但我正在努力删除右括号 ] 。我怎样才能删除那些?我想我很接近了……

#the list to clean
list_strings = ['[ABC1: text1]', '[[DC: this is a text]]', '[ABC-O: potatoes]', '[[C-DF: hello]]']

#remove from [ up to : 
for string in list_strings:
  cleaned = re.sub(r'[\[A-Z\d\-]+:\s*', '', string)
  print(cleaned)

# current output

>>>text1]
>>>this is a text]]
>>>potatoes]
>>>hello]

期望的输出:

text1
this is a text
potatoes
hello

【问题讨论】:

    标签: python regex string re


    【解决方案1】:

    以这种方式编写您的代码。在这里修复 OP 的尝试。您的正则表达式正在做所有事情,唯一的一点就是添加一个 OR 条件,我们可以在其中提及替换 1 次或多次出现的 ]

    import re
    list_strings = ['[ABC1: text1]', '[[DC: this is a text]]', '[ABC-O: potatoes]', '[[C-DF: hello]]']
    for string in list_strings:
      cleaned = re.sub(r'[\[A-Z\d\-]+:\s+|\]+$', '', string)
      print(cleaned)
    

    【讨论】:

      【解决方案2】:

      我会使用 rstrip()split() 功能采用不同的正则表达式方法:

      list_strings = ['[ABC1: text1]', '[[DC: this is a text]]', '[ABC-O: potatoes]', '[[C-DF: hello]]']
      
      cleaned = [s.split(': ')[1].rstrip(']') for s in list_strings]
      print(cleaned) # ['text1', 'this is a text', 'potatoes', 'hello']
      

      【讨论】:

        【解决方案3】:

        我会在这里使用列表推导:

        list_strings = ['[ABC1: text1]', '[[DC: this is a text]]', '[ABC-O: potatoes]', '[[C-DF: hello]]']
        cleaned = [x.split(':')[1].strip().replace(']', '') for x in list_strings]
        print(cleaned)  # ['text1', 'this is a text', 'potatoes', 'hello']
        

        【讨论】:

          【解决方案4】:

          你可以使用

          cleaned = re.sub(r'^\[+[A-Z\d-]+:\s*|]+$', '', string)
          

          请参阅Python demoregex demo

          或者,要确保字符串以[[word: 开头并以]s 结尾,您可以使用

          cleaned = re.sub(r'^\[+[A-Z\d-]+:\s*(.*?)\s*]+$', r'\1', string)
          

          参见this regex demothis Python demo

          而且,如果你只是想提取里面的文本,你可以使用

          # First match only
          m = re.search(r'\[+[A-Z\d-]+:\s*(.*?)\s*]', string)
          if m:
              print(m.group(1))
          
          # All matches
          matches = re.findall(r'\[+[A-Z\d-]+:\s*(.*?)\s*]', string)
          

          请参阅 this regex demothis Python demo

          详情

          • ^ - 字符串开头
          • \[+ - 一个或多个 [ 字符
          • [A-Z\d-]+ - 一个或多个大写 ASCII 字母、数字或 - 字符
          • : - 冒号
          • \s* - 零个或多个空格
          • | - 或
          • ]+$ - 字符串末尾的一个或多个 ] 字符。

          另外,(.*?) 是一个 ID 为 1 的捕获组,它匹配除换行符之外的任何零个或多个字符,尽可能少。替换中的\1指的是存储在这个组内存缓冲区中的值。

          【讨论】:

            猜你喜欢
            • 2022-11-02
            • 1970-01-01
            • 1970-01-01
            • 2010-10-05
            • 1970-01-01
            • 2020-02-14
            • 2018-08-25
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多