Regular Expressions 101

Community Patterns

Community Library Entry

1

Regular Expression
.NET 7.0 (C#)

@"
((\r\n|\r|\n){2,}|\p{Zp}+|\A)^\s*\S
"
gmnN

Description

Finds all paragraphs in the input text, where a paragraph is defined as any occurrence of a non-whitespace character immediately following any of the following and any other preceding whitespace:

  • 2 or more consecutive CRLF sequences
  • 2 or more consecutive CR characters
  • 2 or more consecutive LF characters
  • 1 or more Unicode Paragraph Separator class characters
  • The beginning of the string (matches the first paragraph)

Again, note that whitespace mixed in with the above will not interfere with the matching, as demonstrated by the test text included.

This is intended to be used with the options specified, so be sure to include them for best performance (non-backtracking, multiline, non-capturing, invariant culture).

This will work effectively on any version of .net that supports the included syntax. However, it is intended for use with .net8.0 and up, with the Regex.EnumerateMatches() method, or, more ideally, with .net9.0 and up, using the new Regex.EnumerateSplits() method, to avoid allocations associated with Match objects.

Unicode paragraph separator characters are very rare in practice and support for them is almost non-existent in software, including the Windows Console. Windows Terminal, web browsers, the Windows clipboard, notepad, Visual Studio, and notepad++, all of which fail to handle it in their own ways, none of them actually adding a line when they occur (though notepad++ will show it as PS if you have enabled showing all whitespace).

It is safe to remove |\p{Zp}+ from the pattern, if you do not wish to include those characters in your search. The resulting pattern, as a c# string, would be:

"((\\r\\n|\\r|\\n){2,}|\\A)^\\s*\\S"
Submitted by dodexahedron - 13 days ago (Last modified 13 days ago)