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

2024-04-28 12:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图去掉[]中的前导文本,包括[],如下所示

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

你知道吗输出:-你知道吗

test][R] D123/Peace123456: panic:

预期产量:

[R] D123/Peace123456: panic:

Tags: test文本titlestripprint产量panic前导
1条回答
网友
1楼 · 发布于 2024-04-28 12:15:00

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

相关问题 更多 >