Python 如何去除[]中的所有内容
我试图去掉Python 如何去除[]中的所有内容,python,regex,Python,Regex,我试图去掉[]中的前导文本,包括[],如下所示 title = "[test][R] D123/Peace123456: panic:" print title title = title.strip('[.*]') print title 输出:- test][R] D123/Peace123456: panic: 预期产出: [R] D123/Peace123456: panic: 您需要非贪婪正则表达式从一开始就匹配第一个[],并使用re.sub进行替换: In [10]: tit
[]
中的前导文本,包括[]
,如下所示
title = "[test][R] D123/Peace123456: panic:"
print title
title = title.strip('[.*]')
print title
输出:-
test][R] D123/Peace123456: panic:
预期产出:
[R] D123/Peace123456: panic:
您需要非贪婪正则表达式从一开始就匹配第一个
[]
,并使用re.sub
进行替换:
In [10]: title = "[test][R] D123/Peace123456: panic:"
# `^\[[^]]*\]` matches `[` followed by any character
# except `]` zero or more times, followed by `]`
In [11]: re.sub(r'^\[[^]]*\]', '', title)
Out[11]: '[R] D123/Peace123456: panic:'
# `^\[.*?\]` matches `[`, followed by any number of
# characters non-greedily by `.*?`, followed by `]`
In [12]: re.sub(r'^\[.*?\]', '', title)
Out[12]: '[R] D123/Peace123456: panic:'
str.strip
不接受正则表达式。您需要使用类似于re.sub
(注意,即使str.strip
接受正则表达式,[.*]
将是包含文本
和*
的字符类)我将发布一个答案。不过已经有人打败我了。请参见下面的答案@Jeremyapple。当你说前导文本时,是指第一次出现的[]
,还是只想删除[]
,如果它是文本开头的第一件事?