首页 > 解决方案 > 匹配不以特殊字符开头的行中的换行符

问题描述

当行以 a 开头时,我想匹配所有\n或除了那些 我有这个正则表达式: 例如:\r@(?!^@.*\r*\n*)(\r*\n*)

@text text text 

@text text text
The line break after this text should be matched 
The line break after this text also should be selected 

@this line break should not be selected

所以唯一应该选择的换行符是第 2、4、5、6 和 7 号的换行符。有任何想法吗?

标签: javascriptregexregex-lookarounds

解决方案


像这样?

https://regex101.com/r/bYIpiQ/2

https://regexr.com/4s98n

注意我不选择文本,我替换 \n\r 或 \n 或 \r

const text = document.getElementById("x").innerText;
document.getElementById("x").innerText=text.replace(/(^[^@].*)(\r\n|\r|\n)/gm,"$1<BR/>")
#x { font-family: "Courier New", monospace;
  white-space: pre; }
<div id="x">@line 1: text text text 
line 2:
@line3: text text text
line 4: The line break after this text should be matched 
line 5: The line break after this text also should be selected 
line 6:
@line 7: this line break should not be selected
</div>


推荐阅读