更新:这个问题几乎与此重复
我确定我的问题的答案就在那里,但我无法找到简洁明白的词语.我正在尝试使用JavaScript正则表达式执行以下操作:
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"]
Run Code Online (Sandbox Code Playgroud)
使用JavaScript正则表达式有一个干净的方法吗?显然我可以'自己删除它,但我正在寻找用正则表达式来限制全局匹配分组的正确方法.
jfr*_*d00 79
要使用正则表达式执行此操作,您需要迭代它.exec()以获得多个匹配的组.g具有匹配的标志将仅返回多个完整匹配,而不是您想要的多个子匹配.这是一种方法.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
Run Code Online (Sandbox Code Playgroud)
工作演示:http://jsfiddle.net/jfriend00/VSczR/
对于字符串中的内容有一些假设,你也可以使用它:
var input = "'Warehouse','Local Release','Local Release DA'";
var output = input.replace(/^'|'$/, "").split("','");
Run Code Online (Sandbox Code Playgroud)
工作演示:http://jsfiddle.net/jfriend00/MFNm3/
ele*_*vir 11
String.prototype.matchAll现在现代浏览器和Node.js都得到了很好的支持。可以像这样使用:
const matches = Array.from(myString.matchAll(/myRegEx/g)).map(match => match[1]);
Run Code Online (Sandbox Code Playgroud)
请注意,传递的参数RegExp必须具有全局标志,否则将引发错误。
方便的是,当没有找到匹配项时,这不会抛出错误,因为.matchAll总是返回一个迭代器(而不是.match()返回null)。
对于这个具体的例子:
var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;
var matches = Array.from(input.matchAll(regex)).map(match => match[1]);
// [ "Warehouse", "Local Release", "Local Release DA" ]
Run Code Online (Sandbox Code Playgroud)
不是非常通用的解决方案,因为Javascript不支持lookbehind,但是对于给定的输入,这个正则表达式应该工作:
m = input.match(/([^',]+)(?=')/g);
//=> ["Warehouse", "Local Release", "Local Release DA"]
Run Code Online (Sandbox Code Playgroud)