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,(?:.*,)?(.*),(.*)$
CodePudding user response:
Try this:
,([^,]*),([^,]*$)
It should return only two last groups separated by commas
CodePudding user response:
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']