简体   繁体   English

如何编写一个正则表达式来匹配不跟另一个“ \\ n”的“ \\ n”?

[英]how to write a regex to match a “\n” which is not followed another “\n”?

I want to replace "\\n" with ""(empty string) only when "\\n" is not followed by another "\\n". 我只想在“ \\ n”后面没有另一个“ \\ n”的情况下才用“”(空字符串)替换“ \\ n”。

var text  = "abcdefg
             abcdefg

             1234556
             1234556

             ABCDEFG
             ABCDEFG";

So, if I have a string as the above, I want to make it like this after replacing "\\n"s. 因此,如果我有一个如上所述的字符串,我想在替换“ \\ n”后使其像这样。

"abcdefgabcdefg

 12345561234556

 ABCDEFGABCDEFG";

But, I can't find out how to write a regex to match a "\\n" that is not followed another "\\n". 但是,我不知道如何编写一个正则表达式来匹配未跟在另一个“ \\ n”后面的“ \\ n”。

These are what I tried, but these match both "\\n" and "\\n\\n". 这些是我尝试过的,但是它们都匹配“ \\ n”和“ \\ n \\ n”。

var pattern1 = new RegExp("\\n{1}");
var pattern2 = new RegExp("\\n(?!\\n)");

Could anyone please help me to write a regex in this case? 在这种情况下,有人可以帮我写一个正则表达式吗?

Thanks! 谢谢!

You can match the following: 您可以匹配以下内容:

[^\\\\n](\\\\n)[^\\\\n]

Demo: http://regex101.com/r/eP9xD1 演示: http//regex101.com/r/eP9xD1

You can use /([^\\n])\\n([^\\n])/g and replace it with \\1\\2 . 您可以使用/([^\\n])\\n([^\\n])/g并将其替换为\\1\\2

Usage : 用法

> str = 'abcdefg\nabcdefg\n\n1234556\n1234556\n\nABCDEFG\nABCDEFG';
> str.replace(/([^\n])\n([^\n])/g, '\1\2');
  "abcdefbcdefg

  123455234556

  ABCDEFBCDEFG"

REGEX DEMO 正则演示

FIDDLE 小提琴

您可以使用否定前瞻匹配\\n ,然后再匹配另一个\\n

\n(?!\n)

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

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