简体   繁体   中英

Extracting content between curly braces in Python

I have lines of the form {},{},{},...,{} . The number of curly pairs is variable. I would like to have the content between the curlies in a list of strings.

Example:

Input: {a:b,c:d}

Output: ['a:b,c:d']


Input: {a:b,c:d},{e:f,g:h}

Output: ['a:b,c:d', 'e:f,g:h']

What is the best way to do that?

re.findall(r'\{(.*?)\}', text)

example:

>>> text = '{a:b,c:d},{e:f,g:h}'
>>> re.findall(r'\{(.*?)\}', text)
['a:b,c:d', 'e:f,g:h']
i = '{a:b,c:d},{e:f,g:h}'
[e.strip('{}') for e in i.split('},{')]
# ['a:b,c:d', 'e:f,g:h']

If your requirement is to extracting content between "nth" set of braces in Python - its a simple extension of the above:

import re
qstring="""CREATE TABLE [dbo].[Time_Table]"""

contents_inside_barckets=re.findall(r'\[(.*?)\]', qstr)

Initial output:

['dbo', 'Time_Table']

Contents of the second (index =1) set of brackets:

contents_inside_barckets[1]

Output

'Time_Table'

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