简体   繁体   中英

How to extract substrings between brackets while ignoring those between nested brackets in Python?

I have a string:

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654);'

How can I extract only the substrings that are enclosed between brackets and that do not contain any brackets within each substring? So, from my example I require two outputs: "s2:0.4186036213,s3:0.4186036213" and "s4:0.1429514535,s5:0.1429514535".

You can use regular rexpressions :

import re

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654);'
re.findall(r'\(([^\(\)]*)\)', phy)
# ['s2:0.4186036213,s3:0.4186036213', 's4:0.1429514535,s5:0.1429514535']

This captures everything non-brackety enclosed in opening-closing brackets. It does not, however, validate correct nesting levels.

Try this:

from collections import defaultdict
bracket_dict = defaultdict(int)
bracket_dict_ ={
    '(':')',
    '{':'}',
    '[':']'
}
bracket_dict.update(bracket_dict_)
bracket_list = bracket_dict.keys()

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654);'
inner_items=[]
brackets = []
start_index = None

for i in range(len(phy)):
    if phy[i] in bracket_list:
        start_index = i
        brackets.append(phy[i])

    if brackets:
        if phy[i] == bracket_dict[brackets[-1]]:
            inner_items.append(phy[start_index+1 : i])
            brackets.append(phy[i])
print(inner_items)
#['s2:0.4186036213,s3:0.4186036213', 's4:0.1429514535,s5:0.1429514535']

Use regex:

import re

reg = re.compile(r'[(]([^()]+)[)]')

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654)'

print(reg.findall(phy))

Output :

C:\Users\Desktop>py x.py
['s2:0.4186036213,s3:0.4186036213', 's4:0.1429514535,s5:0.1429514535']

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