看下面的代码:
this.line = Regex.Matches(source, @".+(?<=s(F|D|B|S|T))d+.+").Cast<Match>().Select(match => match.Value).ToList();
foreach (string item in this.line)
{
Console.WriteLine(item + " text");
}
你会期望source
:
HEADER
[
Y22 Z48*2 T4 B12 Desc
X46 Y60*5 S2 D B13 P9
X104 Y124*2 F2 T1 B10 M21
]
...
按如下方式添加:
Y22 Z48*2 T4 B12 Desc text
X46 Y60*5 S2 D B13 P9 text
X104 Y124*2 F2 T1 B10 M21 text
但是我得到了这个:
text48*2 T4 B12 Desc
text60*5 S2 D B13 P9
textY124*2 F2 T1 B10 M21
附加的字符串覆盖item
。这种情况发生的原因,我可以告诉是因为.+
,其中任何字符匹配无限次,直到新的行。但这就是问题的关键。我不知道为什么会发生这种事。想法吗?
打开一个文本文件,提取[和]之间的内容。将它们添加到列表中。然后,对于每一组,我试着做上面提到的匹配。现在我已经通过手动输入建议的字符串测试了这一点,它工作得很好,但对于一个打开的文本不是那么多?会不会是打开的文本弄乱了新行?
fileContents = File.ReadAllText(filename);
source = Regex.Matches(fileContents, @".(?<=[)[^[]]+(?=]).").Cast<Match>().Select(match => match.Value).ToList();
this.line = Regex.Matches(source, @".+(?<=s(F|D|B|S|T))d+.+").Cast<Match>().Select(match => match.Value).ToList();
foreach (string item in this.line)
EDIT2:看到答案。
我认为这不是最优雅的方式,但最终只是逐行浏览源代码并查找是否匹配,如果匹配,则追加到该行。
foreach (string line in source.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) { Regex regex = new Regex(@".+(?<=s(F|D|B|S|T))d+.+"); Match match = regex.Match(line); if (match.Success) Console.WriteLine(line + " text"); }