如何解决在字符串中找到所有匹配的正则表达式模式和匹配索引
|| 我想在AA-AA-AA
主题字符串中找到/AA/
模式。我需要获取匹配的字符串和匹配的位置(索引)。
我看了RegExp.prototype.exec()
。它仅返回第一个匹配项:
/AA/g.exec(\'AA-AA-AA\')
解决方法
exec()
仅返回单个匹配项。要使用g
小数正则表达式获得所有匹配项,您必须反复调用它,例如:
var match,indexes= [];
while (match= r.exec(value))
indexes.push([match.index,match.index+match[0].length]);
,
使用RegExp.prototype.exec()
函数匹配字符串时要小心。构造的regex对象是有状态的,即,每次调用.exec()
都会影响regex实例的lastIndex
属性。因此,在使用正则表达式对象的实例之前,应始终重置“ 9”属性。
let re,findAAs;
re = /AA/;
findAAs = (input) => {
let match;
// `re` is cached instance of regex object.
// Reset `re.lastIndex` every time before using it.
re.lastIndex = 0;
while ((match = re.exec(input)) !== null) {
match.index; // Match index.
match[0]; // Matching string.
}
};
一个诱人的选择是在每次执行时构造regex对象。根据您任务的资源密集程度,这也是一种选择。
let findAAs;
findAAs = (input) => {
let match,re;
re = /AA/;
while ((match = re.exec(input)) !== null) {
match.index; // Match index.
match[0]; // Matching string.
}
};
代替.exec()
的一种实用替代方法是String.prototype.replace()
。
let findAAs,re;
re = /AA/;
findAAs = (input) => {
let match,re;
input.replace(re,(match,index) => {
match; // Matching string.
index; // Match index.
return \'\';
});
};
这种方法的缺点是它构造了主题字符串的副本。
是否应使用它取决于您的任务需要占用大量资源。就我个人而言,我喜欢避免在代码中使用while
块,因此更喜欢.replace()
方法。
, http://jsfiddle.net/mplungjan/MNXvQ/
我认为这比较容易掌握
var str = \"AAbAAcAAd\"
var re = /(AA)/gi;
var t=\"\",cnt=0;
while ((result=re.exec(str))!=null) {
document.write((cnt++)+\":\"+result[1]+\"<br />\")
}
re.lastIndex每次包含位置
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。