Use Regex to extract last row on a text
I need to开发者_JAVA百科 extract only the last row from a multi-line string using regular expressions. I am trying to use a SingleLine pattern like following @"\n(.*?)$" but, unfortunately it extracts the text starting with second line to end. Any hint?
Thanks!
What about something like
@"([^\n\r]*)$"
That means match everything that is not a newline character till the end of the string.
Well, when I think about it, when you don't use the DOTALL modifier then this should be fine
@"(.*)$"
Without this modifier the .
does not match newline characters. So no need for a \n
at the beginning.
Try it without a RegEx
string literal = @"I
am
the
best"; //With \n
string[] lines = literal.Split(new string[] { "\n" }, StringSplitOptions.None);
string lastLine = lines[lines.Length - 1];
Console.WriteLine(lastLine); //Should print "best"
With regex:
Match m = Regex.Match(literal, @"\n*.+$");
Console.WriteLine(m.Value); //Should be @"\nbest"
精彩评论