为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

精慕HU 2019-11-12 10:49:51
有没有办法在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);

}


查看完整回答
反对 回复 2019-11-12
?
手掌心

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

}


查看完整回答
反对 回复 2019-11-12
  • 3 回答
  • 0 关注
  • 1172 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信