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

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);
}

这是我想出的:
// 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);
}

从developer.mozilla.org文档中获取有关String .match()方法的信息:
返回的数组具有额外的输入属性,其中包含已解析的原始字符串。此外,它还具有index属性,该属性表示string中匹配项的从零开始的索引。
当处理非全局正则表达式时(即,g正则表达式上没有标志),返回的值.match()具有index属性...您要做的就是访问它。
var index = str.match(/regex/).index;
这是一个示例,它也可以正常工作:
var str = 'my string here';
var index = str.match(/here/).index;
alert(index); // <- 10
回到IE5,我已经成功进行了测试。
添加回答
举报