简体   繁体   English

捕获并替换多行字符串中出现的前N个模式

[英]Capture and replace first N occurrence of a pattern in a multiline string

I have following string from which i expect to replace the first two occurrences of <br> with a \\n character. 我有以下字符串,我希望从中使用\\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.

I did write my regex here . 我确实在这里写了我的正则表达式。 I am very new to regex and i am sure this is not an optimized solution. 我对regex非常陌生,我敢肯定这不是一个优化的解决方案。 After some tries i was able to select the <br><br> as a capturing group. 经过一些尝试,我能够选择<br><br>作为捕获组。 I want this 3rd capturing group to be my selected match so i can easly replace it with \\n . 我希望该第三捕获组成为我的选定匹配,因此我可以轻松地将其替换为\\n Can someone help me with this? 有人可以帮我弄这个吗?

My expected output is: 我的预期输出是:

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

Try this. 尝试这个。

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

How about: 怎么样:

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

Maybe this regex can help you: 也许此正则表达式可以帮助您:

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

It states that string to match must start with a number followed by . 它指出要匹配的字符串必须以数字开头,后跟。 and some text and then your pattern < br > < br >. 和一些文字,然后是您的图案<br> <br>。 With ?: you create a non capturing group so you replace only < br >< br >. 使用?:创建一个非捕获组,因此仅替换<br> <br>。

Hope this helps. 希望这可以帮助。

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

I think this should work for you: 我认为这应该为您工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM