itd*_*ork 15 javascript ruby regex
这存在吗?
我需要解析一个字符串,如:
the dog from the tree
Run Code Online (Sandbox Code Playgroud)
得到类似的东西
[[null, "the dog"], ["from", "the tree"]]
Run Code Online (Sandbox Code Playgroud)
我可以在Ruby中使用一个RegExp和String#scan
.
JavaScript String#match
无法处理这个,因为它只返回RegExp匹配的内容而不是捕获组,所以返回类似的内容
["the dog", "from the tree"]
Run Code Online (Sandbox Code Playgroud)
因为我String#scan
在Ruby应用程序中多次使用过,如果有一种快速的方法可以在我的JavaScript端口中复制这种行为,那将会很好.
编辑:这是我正在使用的RegExp:http://pastebin.com/bncXtgYA
mel*_*ene 13
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;
};
Run Code Online (Sandbox Code Playgroud)
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"]]
Run Code Online (Sandbox Code Playgroud)
下面是 melpomene 的答案的修改版本,如果合适,返回平面数组。
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;
}
Run Code Online (Sandbox Code Playgroud)
这是另一个实现使用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;
}
Run Code Online (Sandbox Code Playgroud)
工作原理:replace
将在每次匹配时调用回调,并将匹配的子字符串,匹配的组,偏移量和完整字符串传递给它.我们只想要匹配的组,所以我们slice
输出其他参数.