在字符串中查找所有匹配的正则表达式模式和匹配的索引
Find all matching regex patterns and index of the match in the string
我想在AA-AA-AA
主题字符串中找到/AA/
模式。我需要得到匹配的字符串和匹配的位置(索引)。
我看过RegExp.prototype.exec()
。它只返回第一个匹配项:
/AA/g.exec('AA-AA-AA')
exec()
只返回一个匹配项。使用g
获取所有匹配项global regexp,您必须反复调用它,例如:
var match, indexes= [];
while (match= r.exec(value))
indexes.push([match.index, match.index+match[0].length]);
使用RegExp.prototype.exec()
函数匹配字符串时要小心。构造的regex对象是有状态的,即每次调用.exec()
时都会影响regex实例的lastIndex
属性。因此,在使用regex对象的实例之前,应该始终重置lastIndex
属性。
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包含每次的位置
boince答案的替代方法是使用正则表达式的"lastIndex"属性来获取每个匹配的结束索引
var match, indexes= [];
while (match = r.exec(value)) {
indexes.push([match.index, r.lastIndex]);
}
相关文章:
- _water_glass的javascript正则表达式模式
- 需要正则表达式模式的帮助
- 正则表达式模式与各种端点匹配
- JavaScript 中 URL 的正则表达式模式
- Java 与 Javascript 中的正则表达式模式
- 将Javascript正则表达式模式转换为C++std::regex的规则
- 如何从字符串构造正则表达式模式
- 城市和州正则表达式模式
- 如何在字符串上组合JS replace()方法中的3个正则表达式模式
- JavaScript中的递归正则表达式模式
- 正则表达式模式匹配特定单词
- 什么正则表达式模式将从包含的外部HTML文本中提取内部HTML
- 将特定的正则表达式模式与我的字符串匹配
- 为电子邮件开发正则表达式模式
- 将HTML5正则表达式模式转换为JavaScript正则表达式
- 我的正则表达式模式不起作用
- 将字符串中的正则表达式模式替换为依赖于匹配项的替换字符串
- 数字、字母块的正则表达式模式匹配
- Q>javascript 正则表达式模式
- 验证字符串是否为正则表达式模式的开头