I have a comma-separated string of key=value
pairs like this:
foo=1,foo=1,bar=2
In this string I want to capture the value of the first foo
, but only if it's immediately followed by bar=2
.
In this string, the value 1
should be captured:
baz=0,foo=1,bar=2,foo=3,bar=4
In this string, nothing should be captured:
baz=0,foo=1,foo=1,bar=2
My current solution uses a tempered greedy token, but that forces me to duplicate the foo=[^,]*,
part of the regex:
^(?:(?!foo=[^,]*,).)*foo=([^,]*),bar=2(?:,|$)
Is there any way to do this without having to duplicate such a big part of the regex?
It's pretty easy with backtracking control verbs:
(?<![^,])foo=([^,]*)(*COMMIT),bar=2(?![^,])
We match a position not preceded by a non-comma character (i.e. the start of the string or immediately after ,
), followed by foo=
, followed by 0 or more non-comma characters (which we capture). This is the foo=...
part.
We then commit to the first match found and require a ,bar=2
match, not followed by a non-comma character (i.e. a ,
or the end of the string).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments