返回正则表达式match()在Javascript中的位置?

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



精慕HU
浏览 1183回答 3
3回答

慕婉清6462132

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);}
打开App,查看更多内容
随时随地看视频慕课网APP