Regex to match one new line. Regular double line match

I am trying to build a regex that matches a single newline ( \n ).

Likewise, I need another regular expression to match double newline characters ( \n\n ) that are not part of a longer run of newline characters, like \n\n\n or \n\n\n\n\n\n etc.

\n(?!\n) and \n\n(?!\n) too close (they correspond to the last new line (s) in a longer sequence of lines of a new line). What can I do instead?

+6
source share
2 answers

Since JavaScript does not support lookbehind statements, you need to match one extra character in front of your \ n`s and remember to process it later (i.e., restore it if you use regular expression matching to change the original string).

 (^|[^\n])\n(?!\n) 

matches one new line plus the previous character and

 (^|[^\n])\n{2}(?!\n) 

matches two newlines plus the previous character.

So, if you want to replace one \n with <br /> , for example, you need to do

 result = subject.replace(/(^|[^\n])\n(?!\n)/g, "$1<br />"); 

For \n\n this is

 result = subject.replace(/(^|[^\n])\n{2}(?!\n)/g, "$1<br />"); 

Look at regex101

Explanation:

 ( # Match and capture in group number 1: ^ # Either the start of the string | # or [^\n] # any character except newline. ) # End of group 1. This submatch will be saved in $1. \n{2} # Now match two newlines. (?!\n) # Assert that the next character is not a newline. 
+7
source

To match exactly N repetitions of the same character, you will need lookaheads and lookbehind (see Matches exactly N repetitions of the same character ). Since javascript does not support the latter, a pure regex seems impossible. You will need to use a helper function, for example:

 > x = "...a...aa...aaa...aaaa...a...aa" "...a...aa...aaa...aaaa...a...aa" > x.replace(/a+/g, function($0) { return $0.length == 2 ? '@@' : $0; }) " ...a...@ @ ...aaa...aaaa...a...@ @" 
+1
source

Source: https://habr.com/ru/post/950880/


All Articles