How to take only first line from the multiline text

前端 未结 3 578
别跟我提以往
别跟我提以往 2021-02-13 12:26

How can I get only the first line of multiline text using regular expressions?

        string test = @\"just take this first line
        even there is 
                 


        
3条回答
  •  猫巷女王i
    2021-02-13 12:42

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

    . is often touted to match any character, while this isn't totally true. . matches any character only if you use the RegexOptions.Singleline option. Without this option, it matches any character except for '\n' (end of line).

    That said, a better option is likely to be:

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

    And better yet, is Brian Rasmussen's version:

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

提交回复
热议问题