【发布时间】:2013-01-28 15:04:58
【问题描述】:
我试图获取一个由几段组成的多行字符串并将其拆分为几个单独的文本。
我意识到每当我跳过一行时,都会有一个 \n\r 序列。之后我认为每个新行都以 \n 开头并以 \r 结尾。为此,我编写了以下代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication15
{
class Program
{
struct ParagraphInfo
{
public ParagraphInfo(string text)
{
int i;
Text = text;
i = text.IndexOf('.');
FirstSentence = text.Substring(0, i);
}
public string Text, FirstSentence;
}
static void Main(string[] args)
{
int tmp = 0;
int tmp1 = 0;
string MultiParagraphString = @"AA.aa.
BB.bb.
CC.cc.
DD.dd.
EE.ee.";
List<ParagraphInfo> Paragraphs = new List<ParagraphInfo>();
Regex NewParagraphFinder = new Regex(@"[\n][\r]");
MatchCollection NewParagraphMatches = NewParagraphFinder.Matches(MultiParagraphString);
for (int i = 0; i < NewParagraphMatches.Count; i++)
{
if (i == 0)
{
Paragraphs.Add(new ParagraphInfo((MultiParagraphString.Substring(0, NewParagraphMatches[0].Index))));
}
else if (i == (NewParagraphMatches.Count - 1))
{
tmp = NewParagraphMatches[i].Index + 3;
tmp1 = MultiParagraphString.Length - NewParagraphMatches[i].Index - 3;
Paragraphs.Add(new ParagraphInfo(MultiParagraphString.Substring(tmp, tmp1)));
}
else
{
tmp = NewParagraphMatches[i].Index + 3;
tmp1 = NewParagraphMatches[i + 1].Index - NewParagraphMatches[i].Index+3;
Paragraphs.Add(new ParagraphInfo(MultiParagraphString.Substring(tmp, tmp1)));
}
}
Console.WriteLine(MultiParagraphString);
foreach (ParagraphInfo Paragraph in Paragraphs)
{
Console.WriteLine(Paragraph.Text);
}
}
}
}
当我将段落的每个成员一个接一个地打印在整个文本旁边时,出现了一些相当奇怪的东西。段落列表的输出是这样的:
AA.aa.
CC.cc.
DD。
DD.dd.
EE。
EE.ee.
我不明白为什么这种情况一直发生,而且我不明白为什么每次输出都如此不同。
很抱歉,如果它是一团糟,但我真的需要一些帮助。如果有人有更好的想法,请随时分享。
【问题讨论】:
-
仅供参考,在 Windows 上,行终止符是 \r\n,而不是 \n\r。
-
另外,两者都在行的end,而不是在beginning。 .NET 具有独立于平台的
Environment.NewLine,用于跨平台处理换行/回车序列,这就是你应该做的替换,而且,正则表达式,.. 只是,为什么? -
听起来你假设行以 \n 开头并以 \r 结尾是错误的 - 不是 \r\n 只是 CRLF 意味着行应该以 \r\n 结尾- 这样就可以拆分
var paragraphs = someString.Split(Environment.NewLine)?
标签: c# regex string escaping string-literals