Pattern matching regular expression for non-consecutive repeating sequences
P粉563831052
P粉563831052 2023-09-16 20:48:28
0
1
492

I have a long meaningless string where every character is either a number [0-9] or a lowercase letter [a-z] as shown below

"0z8b816ne139z1b948bjk50f9498t139gjj90t7tb3509w6h0r7tbp"

I want a regular expression that can match non-consecutive patterns that appear more than once in a string I want the output to look like this

The bold part is the matching part

"0z8b816ne139z1b948bjk50f9498t139gjj90t7tb3509w6h0r7tbp"

P粉563831052
P粉563831052

reply all(1)
P粉754477325

Regular expression: (.. )(?=.*?(\1))

Reference link

const regex = /(..+)(?=.*?())/gm;

// 使用RegExp构造函数的替代语法
// const regex = new RegExp('(..+)(?=.*?(\1))', 'gm')

const str = `0z8b816ne139z1b948bjk50f9498t139gjj90t7tb3509w6h0r7tbp
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // 避免零宽匹配导致无限循环
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // 可以通过`m`变量访问结果
    m.forEach((match, groupIndex) => {
        console.log(`找到匹配,第${groupIndex}组:${match}`);
    });
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template