Georgios
Georgios

Reputation: 1037

Regular expression to retrieve string parts within parentheses separated by commas

I have a String from which I want to take the values within the parenthesis. Then, get the values that are separated from a comma.

Example: x(142,1,23ERWA31)

I would like to get:

Is it possible to get everything with one regex?

I have found a method to do so, but it is ugly.

This is how I did it in python:

import re
string = "x(142,1,23ERWA31)"
firstResult = re.search("\((.*?)\)", string)
secondResult = re.search("(?<=\()(.*?)(?=\))", firstResult.group(0))
finalResult = [x.strip() for x in secondResult.group(0).split(',')]
for i in finalResult:
    print(i)

142

1

23ERWA31

Upvotes: 1

Views: 1126

Answers (3)

Jongware
Jongware

Reputation: 22457

This works for your example string:

import re

string = "x(142,1,23ERWA31)"
l = re.findall (r'([^(,)]+)(?!.*\()', string)

print (l)

Result: a plain list

['142', '1', '23ERWA31']

The expression matches a sequence of characters not in (,,,) and – to prevent the first x being picked up – may not be followed by a ( anywhere further in the string. This makes it also work if your preamble x consists of more than a single character.

findall rather than search makes sure all items are found, and as a bonus it returns a plain list of the results.

Upvotes: 4

BenH
BenH

Reputation: 61

A little wonky looking, and also assuming there's always going to be a grouping of 3 values in the parenthesis - but try this regex

\((.*?),(.*?),(.*?)\)

To extract all the group matches to a single object - your code would then look like

import re
string = "x(142,1,23ERWA31)"
firstResult = re.search("\((.*?),(.*?),(.*?)\)", string).groups()

You can then call the firstResult object like a list

>> print(firstResult[2])
23ERWA31

Upvotes: 1

Rob Kwasowski
Rob Kwasowski

Reputation: 2780

You can make this a lot simpler. You are running your first Regex but then not taking the result. You want .group(1) (inside the brackets), not .group(0) (the whole match). Once you have that you can just split it on ,:

import re

string = "x(142,1,23ERWA31)"
firstResult = re.search("\((.*?)\)", string)

for e in firstResult.group(1).split(','):
    print(e)

Upvotes: 1

Related Questions