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

2024-06-16 08:27:42 发布

您现在位置: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

Tags: to字符串texthello列表stringisthis
3条回答

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

我会在这里使用列表:

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

用这种方式编写代码。在这里修复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)

相关问题 更多 >