如何从多行文本中仅取第一行

如何才能使用正则表达式获取多行文本的第一行?

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

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

更好的是Brian Rasmussen的版本:

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

如果你只需要第一行,你可以不使用像这样的正则表达式

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

尽管我喜欢正则表达式,但你并不是真的需要它们,所以除非这是一些更大规模的正则表达式练习的一部分,否则我会在这种情况下寻求更简单的解决方案。

试试这个:

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