SomeGuy
SomeGuy

Reputation: 9690

Regex: last occurrence of character before

In this comma delimited text I want to capture just the parts with 'match' in between, and the commas on either side

text,something,hello,house,ymatchy,motor,xmatchx,yoyo

Currently I've got

,.*?match.*?,

However it matches

[1] ,something,hello,house,ymatchy,
[2] ,xmatchx,

I only want the first match the comma directly before the text, not from the beginning - I just want ,ymatchy,

Edit:

Also how would it work if I was matching multiple characters, say the url encoding equivalent of a comma (%2C)

text%2Csomething%2Cmatch%2Chello%2Chouse%2Cy%2match%2y%2Cmotor%2Cxmatchx%2Cyoyo

I would want to match

[1] %2Cmatch%2C
[2] %2Cy%2match%2y%2C
[3] %2Cxmatchx%2C

Upvotes: 0

Views: 782

Answers (2)

SomeGuy
SomeGuy

Reputation: 9690

I've managed to solve my 2nd half

%2C((?!%2C).)*match((?!%2C).)*%2C

I've marked Avinash Raj's answer as accepted, as he answered my original question.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You could use the below regex,

,[^,]*match[^,]*,

DEMO

If you want ,ymatchy, then remove the global flag.

Update:

%2C\w+match\w+%2C

DEMO

Upvotes: 2

Related Questions