在字符串中查找所有匹配的正则表达式模式和匹配的索引 [英] Find all matching regex patterns and index of the match in the string

查看:140
本文介绍了在字符串中查找所有匹配的正则表达式模式和匹配的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 AA-AA-AA 主题字符串中找到 / AA / 模式。我需要获得匹配的字符串和匹配的位置(索引)。

I want to find /AA/ pattern in AA-AA-AA subject string. I need to get the matching string and the position (index) of the match.

我看过 RegExp.prototype.exec() 。它只返回第一场比赛:

I have looked at RegExp.prototype.exec(). It only returns the first match:

/AA/g.exec('AA-AA-AA')


推荐答案

exec()只返回一个匹配项。要使用 g lobal regexp获得所有匹配项,您必须重复调用它,例如:

exec() only returns a single match. To get all matches with a g​lobal regexp, you have to call it repeatedly, eg.:

var match, indexes= [];
while (match= r.exec(value))
    indexes.push([match.index, match.index+match[0].length]);

这篇关于在字符串中查找所有匹配的正则表达式模式和匹配的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆