如何剥离[]中的所有内容

时间:2018-03-15 20:29:18

标签: python regex

我正在尝试删除[]中的主要文字,包括[],如下所示

title  = "[test][R] D123/Peace123456: panic:"
print title
title = title.strip('[.*]')
print title

输出: -

test][R] D123/Peace123456: panic:

预期输出:

[R] D123/Peace123456: panic:

1 个答案:

答案 0 :(得分:6)

您需要非贪婪的正则表达式从头开始匹配[],并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:'