简体   繁体   中英

How do I find the string between two special characters?

For example, I need everything in between the two square brackets. File1

[Home sapiens]
[Mus musculus 1]
[virus 1 [isolated from china]]

So considering the above example, I need everything in between the first and last square brackets.

你可以使用贪婪的正则表达式:

re.search(r'\[(.*)\]', your_string).group(1)

Regular expressions are the most flexible option.

For another approach, you can try string's partition and rpartition methods:

>>> s = "[virus 1 [isolated from china]]"
>>> s.partition('[')[-1].rpartition(']')[0]
'virus 1 [isolated from china]'

Given your sample input, it looks like every line begins and ends with brackets. In which case, forget regexps, this is trivial:

for line in whatever:
    contents = line.strip()[1:-1]

(I've added the strip in case your line source is leaving the newlines in, or there are invisible spaces after the closing bracket in your input. If it's not necessary, leave it out.)

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