JavaScript正则表达式全局匹配组 [英] JavaScript Regex Global Match Groups

查看:167
本文介绍了JavaScript正则表达式全局匹配组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:此问题几乎与 this

我确定我的问题的答案就在那里,但我找不到这些字样简明扼要地表达出来。我正在尝试使用JavaScript正则表达式执行以下操作:

I'm sure the answer to my question is out there, but I couldn't find the words to express it succinctly. I am trying to do the following with JavaScript regex:

var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;

console.log(input.match(regex));

// Actual:
// ["'Warehouse'", "'Local Release'", "'Local Release DA'"]

// What I'm looking for (without the '):
// ["Warehouse", "Local Release", "Local Release DA"]

有没有一种干净的方法来使用JavaScript正则表达式?显然我可以自己删除',但我正在寻找用正则表达式来限制全局匹配分组的正确方法。

Is there a clean way to do this with JavaScript regex? Obviously I could strip out the 's myself, but I'm looking for the correct way to caputre globally matched groupings with regex.

推荐答案

要使用正则表达式执行此操作,您需要使用 .exec()进行迭代,以便获得多个匹配的组。带有匹配的 g 标志只返回多个完整匹配,而不是您想要的多个子匹配。这是使用 .exec()进行此操作的方法。

To do this with a regex, you will need to iterate over it with .exec() in order to get multiple matched groups. The g flag with match will only return multiple whole matches, not multiple sub-matches like you wanted. Here's a way to do it with .exec().

var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;

var matches, output = [];
while (matches = regex.exec(input)) {
    output.push(matches[1]);
}
// result is in output here

工作演示: http://jsfiddle.net/jfriend00/VSczR/

对于字符串中的内容有某些假设,你也可以使用它:

With certain assumptions about what's in the strings, you could also just use this:

var input = "'Warehouse','Local Release','Local Release DA'";
var output = input.replace(/^'|'$/, "").split("','");

工作演示: http://jsfiddle.net/jfriend00/MFNm3/

这篇关于JavaScript正则表达式全局匹配组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆