terrazo
terrazo

Reputation: 85

C# RegEx to match all in the second line

I need a regex to match all in the second line.

First Line
Second Line

I have tried using \n(.*)\n but it returns the empty value.

Match match in Regex.Matches(line, @"\n(.*)\n", RegexOptions.Multiline)

Upvotes: 0

Views: 836

Answers (3)

Abion47
Abion47

Reputation: 24671

With the RegexOptions.MultiLine enabled, you can use the following:

\n^(.*)$

When Multiline is enabled, ^ and $ will match the beginning and the end of a line instead of the beginning and end of a string.

Example: Regex101

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

You don't need regex for that. Just split input string on lines and get line which you need:

var line= @"First Line
Second Line";

var secondLine = line.Split('\n')[1]; // "Second Line"

You can also check count of lines in your string before getting required line by index to avoid IndexOutOfRange exception.

Even with regex it's better to use Split method if you are going to split input by some value (but again, it's an overkill if you are simply splitting by lines without some pattern):

 var secondLine = Regex.Split(line, Environment.NewLine)[1];

Upvotes: 2

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You're trying to match two end of line while the your input only have one.

Change to \n(.*)

Upvotes: 0

Related Questions