代码之家  ›  专栏  ›  技术社区  ›  Clack

如何只从多行文本中提取第一行

  •  14
  • Clack  · 技术社区  · 15 年前

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

            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);
    
    3 回复  |  直到 15 年前
        1
  •  11
  •   Matthew Scharley    15 年前
    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));
    
        2
  •  39
  •   Brian Rasmussen    15 年前

    如果您只需要第一行,就可以不用这样的regex来完成它。

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

    尽管我很喜欢regex,但你并不真正需要它们来做任何事情,所以除非这是一些更大的regex练习的一部分,否则在本例中我会选择更简单的解决方案。

        3
  •  1
  •   Restuta    15 年前

    试试这个:

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