Abdullah AL Shohag
Abdullah AL Shohag

Reputation: 59

regex problem in finding values separated by comma but not the last one in a string in python3

>>> l
'sajo,asjoad,adjai'
>>> lp = re.findall(r'.+?,',l);lp
['sajo,', 'asjoad,']

Here I want the result with the last adjai. But the previous pattern isn't giving me the expexted result. Please help me.

Upvotes: 1

Views: 473

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Surely, use a normal string split method here, the regex is not necessary if it is not required.

However, here is an explanation and a solution.

The .+?, expression matches any one or more characters as few as possible up to and including a comma. The comma is obligatory. That is why you have no match.

You can amend the expression to match either , or the end of string with .+?(?:,|$):

re.findall(r'.+?(?:,|$)',l)

With regex, use [^,]+ to match any one or more characters other than a comma:

import re
l = 'sajo,asjoad,adjai'
print(re.findall(r'[^,]+',l))

Result: ['sajo', 'asjoad', 'adjai']

Upvotes: 1

Abhinav Mathur
Abhinav Mathur

Reputation: 8101

Using string.split(",") is an easy way to get a list of strings separated at commas.

Upvotes: 1

Related Questions