1

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?

Goh-shans
  • 125
  • 11

3 Answers3

1
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']
nosklo
  • 205,639
  • 55
  • 286
  • 290
  • This will include the braces in the results. You need to use lookarounds so they're matched but not returned. – Barmar Jun 26 '18 at 20:51
0
i = '{a:b,c:d},{e:f,g:h}'
[e.strip('{}') for e in i.split('},{')]
# ['a:b,c:d', 'e:f,g:h']
Sunitha
  • 11,422
  • 2
  • 17
  • 22
0

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'
Grant Shannon
  • 3,992
  • 1
  • 39
  • 32