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);
.
往往被吹捧匹配任何字符,而這是不完全正確。 .
只有在使用RegexOptions.Singleline
選項時才匹配任何字符。沒有此選項,它會匹配除'\n'
(行尾)以外的任何字符。
這就是說,一個更好的選擇可能是:
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];
更棒的是,他是布賴恩·拉斯穆森的版本:
string firstline = test.Substring(0, test.IndexOf(Environment.NewLine));
它不工作,你試圖運行你的代碼? – Restuta 2009-10-16 09:18:22
是的,在LINQPad中。你的目的有什麼不對? – 2009-10-16 09:19:18
你的替代解決方案做了很多不是真正必要的工作。如果在這個例子中測試很短,它可能不會成爲一個問題,但是對於一個大的多行字符串來說,這有點浪費。 – 2009-10-16 09:33:41