有没有办法在Java的regex match()结果的字符串中检索(开始)字符位置?
3 回答

慕婉清6462132
TA贡献1804条经验 获得超2个赞
exec返回具有index属性的对象:
var match = /bar/.exec("foobar");
if (match) {
console.log("match found at " + match.index);
}
对于多个匹配项:
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
console.log("match found at " + match.index);
}

手掌心
TA贡献1942条经验 获得超3个赞
这是我想出的:
// Finds starting and ending positions of quoted text
// in double or single quotes with escape char support like \" \'
var str = "this is a \"quoted\" string as you can 'read'";
var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;
while (match = patt.exec(str)) {
console.log(match.index + ' ' + patt.lastIndex);
}
添加回答
举报
0/150
提交
取消