简体   繁体   中英

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".

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.

"abcdefgabcdefg

 12345561234556

 ABCDEFGABCDEFG";

But, I can't find out how to write a regex to match a "\\n" that is not followed another "\\n".

These are what I tried, but these match both "\\n" and "\\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

You can use /([^\\n])\\n([^\\n])/g and replace it with \\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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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