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

Jer*_*ple 4 python regex

我试图剥离内部的主要文本,[]包括[]如下

title  = "[test][R] D123/Peace123456: panic:"
print title
title = title.strip('[.*]')
print title
Run Code Online (Sandbox Code Playgroud)

输出: -

test][R] D123/Peace123456: panic:
Run Code Online (Sandbox Code Playgroud)

预期产量:

[R] D123/Peace123456: panic:
Run Code Online (Sandbox Code Playgroud)

hee*_*ayl 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:'
Run Code Online (Sandbox Code Playgroud)