[英]Regex to list, to console print append is misbehaving due to match any character
看下面的代码:
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"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.