【问题标题】:Capture and replace first N occurrence of a pattern in a multiline string捕获并替换多行字符串中模式的前 N ​​次出现
【发布时间】:2018-07-02 07:39:27
【问题描述】:

我有以下字符串,我希望用\n 字符替换前两次出现的<br>

<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。我对正则表达式很陌生,我确信这不是一个优化的解决方案。 经过一些尝试,我能够选择&lt;br&gt;&lt;br&gt; 作为捕获组。 我希望这第三个捕获组成为我选择的匹配项,因此我可以轻松地将其替换为 \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})/)
);  

【问题讨论】:

  • 我给你做了一个sn-p。预期的输出究竟是什么?
  • 目前还不清楚你想要做什么:str.replace('&lt;br&gt;&lt;br&gt;', '\n')
  • 谢谢你们的回复。我已经编辑了我的问题,以向您展示我的预期输出。
  • @Mark_M 我正在​​尝试检测

    是否位于列表末尾。如果我发现这种模式,我希望它被换行符替换。

标签: javascript regex


【解决方案1】:

试试这个。

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】:

    怎么样:

    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"));

    【讨论】:

    • @Kooilnc。您的解决方案很接近,但它选择了列表上方和下方的所有
      。你能看看我发布的更新正则表达式链接吗?谢谢。
    【解决方案3】:

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

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

    它指出要匹配的字符串必须以数字开头,后跟 .和一些文字,然后是你的模式

    。使用 ?: 您创建了一个非捕获组,因此您只替换 .

    希望这会有所帮助。

    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'));

    【讨论】:

    • 解决方案也选择出现的数字。我只想匹配和替换前 2 个
      标签。
    【解决方案4】:

    我认为这应该适合你:

    str.replace(//g, '\n');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2017-02-26
      • 2018-03-24
      • 1970-01-01
      • 2013-02-20
      相关资源
      最近更新 更多