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

时间:2017-10-16 22:14:42

标签: c# regex

我使用Regex返回两行文本,但它返回带有附加文本的换行符。

//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 个答案:

答案 0 :(得分:2)

您可以使用

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

<强>详情

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

这里使用.Trim()来修剪可能的CR符号的结果(因为在.NET正则表达式中,.也匹配CR符号。