3

I have a string that I expect to be formatted like so:

{List:[Names:a,b,c][Ages:1,2,3]}

My query looks like this in javascript:

var str = "{List:[Names:a,b,c][Ages:1,2,3]}";
var result = str.match(/^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g);

Note: I recognize that with this regex it would pass with something like "Ages:,,,", but I'm not worried about that at the moment.

I was expecting to get this back:

result[0] = "{List:[Names:a,b,c][Ages:1,2,3]}"
result[1] = "a,b,c"
result[2] = "1,2,3"

But no matter what I seem to do to the regular expression, it refuses to return an array of more than one match, I just get the full string back (because it passes, which is a start):

result = ["{List:[Names:a,b,c][Ages:1,2,3]}"]

I've looked through a bunch of questions on here already, as well as other 'intro' articles, and none of them seem to address something this basic. I'm sure it's something foolish that I've overlooked, but I truly have no idea what it is :(

4

2 回答 2

4

所以这是在 JavaScript 正则表达式中应用全局标志的方式不同。

.match中,全局标志(/g最后)将返回正则表达式与字符串匹配的每个事件的数组。如果没有该标志,.match将返回字符串中所有分组的数组。

例如:

var str = "{List:[Names:a,b,c][Ages:1,2,3]}";
str += str;
// removed ^ and $ for demonstration purposes
var results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/g)
console.log(results)
// ["{List:[Names:a,b,c][Ages:1,2,3]}", "{List:[Names:a,b,c][Ages:1,2,3]}"]
str = "{List:[Names:a,b,c][Ages:1,2,3]}{List:[Names:a,b,c][Ages:3,4,5]}";
results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/g);
console.log(results)
//["{List:[Names:a,b,c][Ages:1,2,3]}", "{List:[Names:a,b,c][Ages:3,4,5]}"]

现在,如果我们删除该/g标志:

// leaving str as above
results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/);
console.log(results)
//["{List:[Names:a,b,c][Ages:1,2,3]}", "a,b,c", "1,2,3"]

作为说明为什么regex.exec起作用的说明,那是因为:

如果正则表达式不包含 g 标志,则返回与 regexp.exec(string) 相同的结果。

于 2013-08-19T17:01:44.487 回答
2

您正在寻找表格needle.exec(haystack)

从我的控制台:

> haystack = "{List:[Names:a,b,c][Ages:1,2,3]}";
"{List:[Names:a,b,c][Ages:1,2,3]}"

> needle = /^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g ;
/^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g

> needle.exec(haystack);
["{List:[Names:a,b,c][Ages:1,2,3]}", "a,b,c", "1,2,3"]
于 2013-08-19T16:51:36.523 回答