JavaScript相当于Ruby的String#scan

这存在吗?

我需要解析一个字符串,如:

the dog from the tree 

得到类似的东西

 [[null, "the dog"], ["from", "the tree"]] 

我可以用Ruby做一个RegExp和String#scan

JavaScript的String#match无法处理,因为它只返回RegExp匹配的内容,而不是捕获组,因此返回类似

 ["the dog", "from the tree"] 

因为我在Ruby应用程序中多次使用String#scan ,如果有一种快速方法可以在我的JavaScript端口中复制此行为,那将会很好。

编辑:这是我正在使用的RegExp: http : //pastebin.com/bncXtgYA

 String.prototype.scan = function (re) { if (!re.global) throw "ducks"; var s = this; var m, r = []; while (m = re.exec(s)) { m.shift(); r.push(m); } return r; }; 

这是使用String.replace的另一个实现:

 String.prototype.scan = function(regex) { if (!regex.global) throw "regex must have 'global' flag set"; var r = [] this.replace(regex, function() { r.push(Array.prototype.slice.call(arguments, 1, -2)); }); return r; } 

工作原理: replace将在每次匹配时调用回调,并将匹配的子串,匹配的组,偏移量和完整的字符串传递给它。 我们只想要匹配的组,所以我们slice出其他参数。

只有在指定了捕获组时,ruby的scan()方法才会返回嵌套数组。 http://ruby-doc.org/core-2.5.1/String.html#method-i-scan

 a = "cruel world" a.scan(/\w+/) #=> ["cruel", "world"] a.scan(/.../) #=> ["cru", "el ", "wor"] a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]] a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]] 

下面是melpomene的修改版本,如果合适的话,返回平面arrays的答案。

 function scan(str, regexp) { if (!regexp.global) { throw new Error("RegExp without global (g) flag is not supported."); } var result = []; var m; while (m = regexp.exec(str)) { if (m.length >= 2) { result.push(m.slice(1)); } else { result.push(m[0]); } } return result; }