2009-10-16 62 views
13

如何僅使用正則表達式獲取多行文本的第一行?如何從多行文本中僅取第一行

 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); 

回答

11
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)); 
+0

它不工作,你試圖運行你的代碼? – Restuta 2009-10-16 09:18:22

+0

是的,在LINQPad中。你的目的有什麼不對? – 2009-10-16 09:19:18

+1

你的替代解決方案做了很多不是真正必要的工作。如果在這個例子中測試很短,它可能不會成爲一個問題,但是對於一個大的多行字符串來說,這有點浪費。 – 2009-10-16 09:33:41

1

試試這個:

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

如果你只需要第一行,你可以用出使用這樣

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

,因爲我喜歡regexs儘可能多一個正則表達式,你並不真正需要他們的一切,因此除非這是一些較大的正則表達式工作的一部分,我會去爲這個簡單的解決方案案件。

+0

請在投票時進行評論。 – 2009-10-16 09:19:41

+0

(免責聲明:我是誰upvoted你的人)但它可能是因爲它不是一個正則表達式。 – 2009-10-16 09:22:30

+5

這是最好的解決方案。這樣一個簡單的任務不需要正則表達式,而且這也是有效的。 – Noldorin 2009-10-16 09:23:07

1

我的2美分:

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

相關問題