I want to use JavaScript's regular expression something like this
/marker\d+"?(\w+)"?\s/gi
In a string like this:
IDoHaveMarker1"apple" IDoAlsoHaveAMarker352pear LastPointMakingmarker3134"foo"
And I want it to return an array like this:
[ "apple", "pear", "foo" ]
The quotes are to make clear they are strings. They shouldn't be in the result.
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]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.