1

I have a need to get the last two elements of a comma separated string of any number of elements, that also starts with a specified value.

Here is an example of how I expect it to work.

def process(pattern, string):
  part1, part2 = None, None
  match = re.search(pattern, string)
  if match:
    part1 = match.group(1)
    part2 = match.group(2)
return part1, part2

regex_search = ?
string1 = must,have,blah,blah,blah,blah,grab,this
string2 = must,have,grab,that
string3 = wrong,have,drop,this

print(process(regex_search, string1)
print(process(regex_search, string2)
print(process(regex_search, string3)

result is supposed to be

('grab', 'this')
('grab', 'that')
(None, None)

My regexp and what its currently getting

regex_search = '^must,have,(.*)\\,(.*)$'

('blah,blah,blah,blah,grab', 'this')
('grab', 'that')
(None, None)

Edit: Thanks Wiktor!! Solution below.

^must,have,(?:.*,)?(.*),(.*)$
2
  • 2
    Maybe ^must,have,(?:.*,)?(.*),(.*)$? Or ^must,have,(?:.*,)?([^,]*),([^,]*)$ Commented Oct 13, 2022 at 17:39
  • 3
    And a CSV parser is unsuitable why exactly? Commented Oct 13, 2022 at 17:42

2 Answers 2

4

Try this:

,([^,]*),([^,]*$)

It should return only two last groups separated by commas

Sign up to request clarification or add additional context in comments.

Comments

1

instead of regex we can also use a for loop to grap the required data.

lst = ['must,have,blah,blah,blah,blah,grab,this','must,have,grab,that','wrong,have,drop,this']
for item in lst:
    if item.startswith('must'):
        res = item.split(',')[-2:]
        print(res)

result:

['grab', 'this']
['grab', 'that']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.