如何使用正则表达式仅获取第一行多行文本?
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);
Run Code Online (Sandbox Code Playgroud)
Bri*_*sen 39
如果你只需要第一行,你可以不使用像这样的正则表达式
var firstline = test.Substring(0, test.IndexOf(Environment.NewLine));
Run Code Online (Sandbox Code Playgroud)
尽管我喜欢正则表达式,但你并不是真的需要它们,所以除非这是一些更大的正则表达式练习的一部分,否则在这种情况下我会选择更简单的解决方案.
Mat*_*ley 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);
Run Code Online (Sandbox Code Playgroud)
.经常被吹捧为匹配任何角色,而这并非完全正确..仅在使用该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];
Run Code Online (Sandbox Code Playgroud)
更好的是Brian Rasmussen的版本:
string firstline = test.Substring(0, test.IndexOf(Environment.NewLine));
Run Code Online (Sandbox Code Playgroud)