search

Home  >  Q&A  >  body text

Pattern matching regular expression for non-consecutive repeating sequences

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粉563831052P粉563831052439 days ago495

reply all(1)I'll reply

  • P粉754477325

    P粉7544773252023-09-17 09:59:12

    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}`);
        });
    }

    reply
    0
  • Cancelreply