admin管理员组

文章数量:1336587

I have a regex which searches for a newline symbol:

\r?\n|\r

And two examples:

#Example-1#
The correct answer is (B) 2 to 3. jfbgfdgdf sgdsgsd.

jfbgfdgdf sgdsgsd.
#End Example-1#

#Example-2#
The correct answer is (B) 2 to 3. jfbgfdgdf sgdsgsd.
jfbgfdgdf sgdsgsd.
#End Example-2#

Demo:

I need to update a regex, so it finds only multiple instances of newline symbol, like these in Example-1 between text lines and not the one between text lines in Example-2

I have a regex which searches for a newline symbol:

\r?\n|\r

And two examples:

#Example-1#
The correct answer is (B) 2 to 3. jfbgfdgdf sgdsgsd.

jfbgfdgdf sgdsgsd.
#End Example-1#

#Example-2#
The correct answer is (B) 2 to 3. jfbgfdgdf sgdsgsd.
jfbgfdgdf sgdsgsd.
#End Example-2#

Demo: https://regex101./r/zQ3nR3/1

I need to update a regex, so it finds only multiple instances of newline symbol, like these in Example-1 between text lines and not the one between text lines in Example-2

Share Improve this question edited Oct 7, 2015 at 12:52 R-J asked Oct 7, 2015 at 12:23 R-JR-J 9361 gold badge7 silver badges24 bronze badges 2
  • 2 Like (\r?\n|\r){2,}? – Wiktor Stribiżew Commented Oct 7, 2015 at 12:25
  • you could use curly brackets like this \\s{2,}. This does only find two or more instances of a whitespace – SomeJavaGuy Commented Oct 7, 2015 at 12:26
Add a ment  | 

2 Answers 2

Reset to default 3

To match just the multiple linebreaks inside #Example text, use a limiting quantifier {2,} applied to (?:\r?\n|\r) and restrict it with a look-ahead:

(\r?\n|\r){2,}(?!#Example-\d)

See demo

The (?!#Example-\d) look-ahead returns a match only if there is no #Example-+digit after the multiple newline symbols.

(\r?\n|\r)\d*(\r?\n|\r)

should do the trick, see https://regex101./r/zQ3nR3/3

It searches for a newline in the way you did, followed by any amount of whitespace, followed by another empty line.


((\r?\n|\r)\d*)+(\r?\n|\r)

would search for multiple empty lines (they could contain any whitespace, though), see https://regex101./r/zQ3nR3/4

本文标签: javascriptRegexsearching for multiple newlinesStack Overflow