tags:

views:

146

answers:

4

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);
+2  A: 
Matthew Scharley
It is not working, have you tried to run your code?
Restuta
Yes, in LINQPad. What's wrong on your end?
Matthew Scharley
Your alternative solution does a lot of work that isn't really necessary. If test is short as in the example it probably isn't going to be a problem, but for a big multi-line string it is a bit of waste.
Brian Rasmussen
@Brian, I agree. I didn't change it to copy yours in the hopes that yours would be accepted, but I think I might 'borrow' it now.
Matthew Scharley
@Matthew: No problem.
Brian Rasmussen
A: 

Try this one:

Match m = Regex.Match(test, @".*\n", RegexOptions.Multiline);
Restuta
+11  A: 

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.

Brian Rasmussen
Please comment when down voting.
Brian Rasmussen
(Disclaimer: I'm the person who upvoted you) But it's probably because it's not a regex.
Matthew Scharley
This is the best solution. No regex needed for a such a simple task, and this is also efficient.
Noldorin
@Matthew: true, but shouldn't we allow for useful alternatives as well when answering?
Brian Rasmussen
The question is " How to do it WITH regex" so you can't know why author needs this and you answer WITHOUT regex can be completely useless.
Restuta
@Restuta: Fair point, but personally I would still find an answer like the one I provided useful, as it provides an alternative solution to the problem.
Brian Rasmussen
@Brian, oh I totally agree with you, hence the upvote.
Matthew Scharley
1 down vote - 8 upvotes. Good, ain't it?
Amarghosh
A: 

My 2 cents:

[^\n]*(\n|$)

skwllsp