代码之家  ›  专栏  ›  技术社区  ›  Srdjan M.

正则表达式打印换行符C#

  •  2
  • Srdjan M.  · 技术社区  · 8 年前

    我使用正则表达式返回两行文本,但它返回带有额外文本的换行符。

    //Text is located in txt file and contains
    I've been meaning to talk with you.
    I've been meaning to talk with you.
    I've been meaning to talk with you.
    
    string text = File.ReadAllText(@"C:\...\1.txt");
    
    Regex unit = new Regex(@"(?<Text>.+(\r\n){1}.+)");
    MatchCollection mc = unit.Matches(text);
        foreach (Match m in mc)
             foreach (Group g in m.Groups)
                  Console.WriteLine(g.Value);
    

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  2
  •   Wiktor Stribiżew    8 年前

    您可以使用

    var m = Regex.Match(text, @"^.+(?:\n.+)?");
    if (m.Success) 
    {
        Console.Write(m.Value.Trim());
    }
    

    细节

    • ^
    • .+ -除LF符号外的任何1+字符
    • (?:\n.+)? -可选序列:
      • \n -换行符
      • .+ -除LF符号外的任何1+字符

    这个 .Trim() 此处用于从可能的CR符号中修剪结果(因为在.NET正则表达式中, . 也匹配CR符号。