Clack
Clack

Reputation: 945

How to take only first line from the multiline text

How can I get only the first line of multiline text using regular expressions?

        string test = @"just take this first line
        even there is 
        some more
        lines here";

        Match m = Regex.Match(test, "^", RegexOptions.Multiline);
        if (m.Success)
            Console.Write(m.Groups[0].Value);

Upvotes: 16

Views: 12355

Answers (4)

TarmoPikaro
TarmoPikaro

Reputation: 5243

This kind of line replaces rest of text after linefeed with empty string.

test = Regex.Replace(test, "(\n.*)$", "", RegexOptions.Singleline);

This will work also properly if string does not have linefeed - then no replacement will be done.

Upvotes: 0

Matthew Scharley
Matthew Scharley

Reputation: 132324

string test = @"just take this first line
even there is 
some more
lines here";

Match m = Regex.Match(test, "^(.*)", RegexOptions.Multiline);
if (m.Success)
    Console.Write(m.Groups[0].Value);

. is often touted to match any character, while this isn't totally true. . matches any character only if you use the RegexOptions.Singleline option. Without this option, it matches any character except for '\n' (end of line).

That said, a better option is likely to be:

string test = @"just take this first line
even there is 
some more
lines here";

string firstLine = test.Split(new string[] {Environment.NewLine}, StringSplitOptions.None)[0];

And better yet, is Brian Rasmussen's version:

string firstline = test.Substring(0, test.IndexOf(Environment.NewLine));

Upvotes: 11

Brian Rasmussen
Brian Rasmussen

Reputation: 116411

If you just need the first line, you can do it without using a regex like this

var firstline = test.Substring(0, test.IndexOf(Environment.NewLine));

As much as I like regexs, you don't really need them for everything, so unless this is part of some larger regex exercise, I would go for the simpler solution in this case.

Upvotes: 40

Restuta
Restuta

Reputation: 5903

Try this one:

Match m = Regex.Match(test, @".*\n", RegexOptions.Multiline);

Upvotes: 1

Related Questions