代码之家  ›  专栏  ›  技术社区  ›  Priyesh Diukar

捕获并替换多行字符串中模式的前n个匹配项

  •  1
  • Priyesh Diukar  · 技术社区  · 8 年前

    我有以下字符串,希望从中替换前两个出现的 <br> 用一个 \n 性格。

    <br><br><br>. Do not replace <br> here.
    1. One
    2. Two
    3. Three<br><br><br>End of List. Replace first two <br> with \n
    New line follows.
    <br><br><br>. Do not replace <br> here.
    

    我写了我的正则表达式 here 是的。我对regex很陌生,我确信这不是一个优化的解决方案。 经过一些尝试,我能够选择 <br><br> 作为一个捕捉组。 我希望这第三个拍摄组是我选择的匹配,这样我就可以轻松地用 \ n个 是的。 有人能帮我吗?

    我的预期产出是:

    <br><br><br>. Do not replace <br> here.
    1. One
    2. Two
    3. Three\n<br>End of List. Replace first two <br> with \n
    New line follows.
    <br><br><br>. Do not replace <br> here.
    

    var str = `1. One
    2. Two
    3. Three<br><br><br>End of List
    New line follows
    `
    
    console.log(
      str.match(/[\n\r].*(\d\.\s+)(?!.*[\n\r](\d\.\s+)).*((<br\s*\/?>){2})/)
    );  
    4 回复  |  直到 8 年前
        1
  •  2
  •   Joven28    8 年前

    试试这个。

    let str = `<br><br><br>. Do not replace <br> here.
    1. One
    2. Two
    3. Three<br><br><br>End of List. Replace first two <br> with \n
    New line follows.
    <br><br><br>. Do not replace <br> here.`;
    console.log(str.replace(/(?<=[0-9]+\..*?)(<br>){2}/g, "\n"));
        2
  •  1
  •   KooiInc    8 年前

    怎么样:

    const initialString = `1. One
    2. Two
    3. Three<br><br><br>End of List
    New line follows
    `;
    console.log(initialString.replace(/<br>?<br>/g, "\n\n"));
    
    // or do you mean:
    console.log(initialString.replace(/<br>?(<br>){1,}/g, "\n\n"));
        3
  •  1
  •   Alex G    8 年前

    也许这个正则表达式可以帮助您:

    /(?:(([0-9])+.([\w]| ))*)<br><br>/g
    

    它指出要匹配的字符串必须以后跟的数字开头。还有一些文本,然后是您的模式<br><br>。和?:您创建了一个非捕获组,因此只替换<br><br>。

    希望这有帮助。

    var str = `1. One
    2. Two
    3. Three<br><br><br>End of List
    New line follows
    `;
    
    console.log(str.replace(/(?:(([0-9])+.([\w]| ))*)<br><br>/g, '\n'));
        4
  •  0
  •   Rupinder    8 年前

    我认为这应该对你有用:

    str.replace(/<\br><\br>/g,“\n”);