如何在 Python 中使用正则表达式删除右方括号?

How can I remove the closing square bracket using regex in Python?

我有一个混乱的字符串列表 (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

你可以使用

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

参见Python demo and the regex demo

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

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

参见 this regex demo and this 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 demo and this Python demo

详情

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

此外,(.*?) 是 ID 为 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)

我会在这里使用列表理解:

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']

我会使用 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']