Regular Expression To Find Complex Markers
I want to use JavaScript's regular expression something like this /marker\d+'?(\w+)'?\s/gi In a string like this: IDoHaveMarker1'apple' IDoAlsoHaveAMarker352pear LastPointMakingma
Solution 1:
If you are asking about how to actually use the regex:
To get all captures of multiple (global) matches you have to use a loop and exec
in JavaScript:
var regex = /marker\d+"?(\w+)/gi;
var result = [];
var match;
while (match = regex.exec(input)) {
result.push(match[1]);
}
(Note that you can omit the trailing "?\s?
if you are only interested in the capture, since they are optional anyway, so they don't affect the matched result.)
And no, g
will not allow you to do all of that in one call. If you had omitted g
then exec
would return the same match every time.
As Blender mentioned, if you want to rule out things like Marker13"something Marker14bar
(unmatched "
) you need to use another capturing group and a backreference. Note that this will push your desired capture to index 2
:
var regex = /marker\d+("?)(\w+)\1/gi;
var result = [];
var match;
while (match = regex.exec(input)) {
result.push(match[2]);
}
Post a Comment for "Regular Expression To Find Complex Markers"