在字符串中查找所有匹配的正则表达式模式和匹配的索引

Find all matching regex patterns and index of the match in the string

本文关键字:正则表达式 模式 索引 字符串 查找      更新时间:2023-09-26

我想在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]);
}