Jayesh Dhandha
Jayesh Dhandha

Reputation: 2119

Special regex for String in python

I have a string like below.

s = ({[test1, test2 ; test3 (New) ]})

Now I have a regex which will remove brackets and convert it into the list. Even if there are separated with a;b,c like. REGEX:

output = [i for i in re.split(r'\s*[(){}<>\[\],;\'"]\s*', s) if i]

But this regex is removing brackets from items of the list as well. ((New) in my case)

How to apply this regex for beginnig and end of the string. I know it can be done using ^ but not sure how?

Expected Output

['test1', 'test2', 'test3 (New)' ]

Output coming from above regex

['test1', 'test2', 'test3', 'New']

Any help?

Upvotes: 0

Views: 207

Answers (2)

SpghttCd
SpghttCd

Reputation: 10860

s = '({[test1, test2 ; test3 (New) ]})'

Based on your comment below I assume that the number of opening brackets of the whole string is equal to the number of closing brackets.

So removing the outer brackets first needs to know their number:

m = re.match('[({[]*', s)
n_brckt = m.span()[1] - m.span()[0]

Then remove the outer brackets ( - dependent on if there were found any...):

if n_brckt > 0:
    s = s[n_brckt:-n_brckt]
s = s.strip()

In: s
Out: 'test1, test2 ; test3 (New)'

Then you can split at all occurences of commas or colons optionally followed by a space:

In: re.split('[,;]+ *', s)
Out: ['test1', 'test2', 'test3 (New)']

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Using re.search

import re
s = "({[test1, test2 ; test3 (New) ]})"
m = re.search("\[(.*?)\]", s)
if m:
    #print(m.group(1).replace(";", ",").split(",")) 
    print([i.strip() for i in m.group(1).replace(";", ",").split(",")])

Output:

['test1', 'test2', 'test3 (New)']

Upvotes: 1

Related Questions