匹配不是以特殊字符开头的行中的换行符

Match line breaks in lines that are not starting with a special character

我想匹配所有 \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中的换行符。 有什么想法吗?

像这样?

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

https://regexr.com/4s98n

注意我没有 SELECT 文本,我替换 \n\r or\n 或 \r

const text = document.getElementById("x").innerText;
document.getElementById("x").innerText=text.replace(/(^[^@].*)(\r\n|\r|\n)/gm,"<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>

你可以尝试这样的事情。使用 split 以换行符‘\n’分割字符串,这将替换字符串中的所有换行符和 return 字符串数组。现在遍历数组并检查该行是否以 ‘@’然后在行尾追加换行符。

使用这种方法,您可以在任何需要的地方添加换行符。

let values = `@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`;

values = values.split(/\n/); // split all with line break

values.forEach((value, index) => {
  if (value.match(/^@.*/gm)) {
    values[index] = value + " <br>"; // or add \n
  } 
});
document.getElementById('result').innerHTML = values.join('');
<div id="result"></div>