Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match full lines of text excluding crlf

Tags:

c#

.net

regex

How would a regex pattern to match each line of a given text be?

I'm trying ^(.+)$ but it includes crlf...

like image 988
Poull Avatar asked May 10 '11 21:05

Poull


3 Answers

Just use RegexOptions.Multiline.

Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.

Example:

var lineMatches = Regex.Matches("Multi\r\nlines", "^(.+)$", RegexOptions.Multiline);
like image 119
František Žiačik Avatar answered Oct 26 '22 22:10

František Žiačik


I'm not sure what you mean by "match each line of a given text" means, but you can use a character class to exclude the CR and LF characters:

[^\r\n]+
like image 22
Nicole Avatar answered Oct 26 '22 23:10

Nicole


The wording of your question seems a little unclear, but it sounds like you want RegexOptions.Multiline (in the System.Text.RegularExpressions namespace). It's an option you have to set on your RegEx object. That should make ^ and $ match the beginning and end of a line rather than the entire string.

For example:

Regex re = new Regex("^(.+)$", RegexOptions.Compiled | RegexOptions.Multiline);
like image 29
Justin Morgan Avatar answered Oct 27 '22 00:10

Justin Morgan