0

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.

4

1 回答 1

4

如果您询问如何实际使用正则表达式:

要获取多个(全局)匹配的所有捕获,您必须使用循环并exec在 JavaScript 中:

var regex = /marker\d+"?(\w+)/gi;
var result = [];
var match;
while (match = regex.exec(input)) {
    result.push(match[1]);
}

(请注意,"?\s?如果您只对捕获感兴趣,则可以省略尾随,因为它们无论如何都是可选的,因此它们不会影响匹配的结果。)

不,g不允许您在一个电话中完成所有这些。如果您省略了gthenexec每次都会返回相同的匹配项。

正如 Blender 提到的,如果您想排除Marker13"something Marker14bar(unmatched ") 之类的事情,您需要使用另一个捕获组和反向引用。请注意,这会将您想要的捕获推送到 index 2

var regex = /marker\d+("?)(\w+)\1/gi;
var result = [];
var match;
while (match = regex.exec(input)) {
    result.push(match[2]);
}
于 2012-12-12T23:35:41.000 回答