简体   繁体   中英

How to strip of everything in []

I am trying to strip of the leading text inside [] including the [] as below

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

OUTPUT:-

test][R] D123/Peace123456: panic:

EXPECTED OUTPUT:

[R] D123/Peace123456: panic:

You need non-greedy Regex to match first [] from start, and re.sub to do the replacements:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM