【问题标题】:Match line breaks in lines that are not starting with a special character匹配不以特殊字符开头的行中的换行符
【发布时间】:2020-01-15 13:40:52
【问题描述】:

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

【问题讨论】:

  • "\n\r" 是一个非标准的换行符,除此之外,你的文本是多行的。你能详细说明一下吗?
  • 我只是在示例中添加了 \n 和 \r 以使其清楚,是的,我的文本是多行的,我想我可以添加 m 标志,对吗?如果它适用于一行
  • 您确实意识到,例如“\n”是换行符,而“\r”在某种程度上也是行分隔符?
  • 什么平台使用\n\r作为换行符? AFAIK Linux/Unix 使用\n,Mac 使用\r,Windows 使用\r\n
  • 如上所述,“\n\r”是非标准的。 "\r" 只用在旧的 Mac 上(我不认为他们现在这样做了?)。但是,由于那个遗留原因,例如多行标志m 仍将“\r”视为行分隔符。当在具有 CRLF 行结尾的字符串上使用它时,这会导致非常烦人的行为。

标签: javascript regex regex-lookarounds


【解决方案1】:

像这样?

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>

【讨论】:

  • 谢谢,但它不起作用,我没有得到与你相同的匹配项,我得到了所有有换行符且不以@开头的文本
  • 我已经编辑了我的问题,所以我希望现在很清楚。你有什么想法吗?
  • 我用regexr.com 测试但我得到不同的结果..
  • 匹配所有文本,我只想匹配换行符,因为我想用另一个字符串替换它们..
  • 我的代码只更改选定的 \r\n 并保留文本
【解决方案2】:

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

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

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('');
&lt;div id="result"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多