简体   繁体   English

正则表达式要列出,要控制台打印附加,由于匹配任何字符而出现异常

[英]Regex to list, to console print append is misbehaving due to match any character

Looking at the code below: 看下面的代码:

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");
            }

You would expect this source : 您会期望此source

HEADER
[    
Y22 Z48*2 T4 B12 Desc
X46 Y60*5 S2 D B13 P9
X104 Y124*2 F2 T1 B10 M21
]
...

to be appended as follows: 附加如下:

Y22 Z48*2 T4 B12 Desc text
X46 Y60*5 S2 D B13 P9 text
X104 Y124*2 F2 T1 B10 M21 text

But I am getting this: 但是我得到这个:

 text48*2 T4 B12 Desc
 text60*5 S2 D B13 P9
 textY124*2 F2 T1 B10 M21

The appended string is overwriting the item . 附加字符串覆盖item The reason this is happening from what I can tell is because of the .+ where any character is matched infinite times until new line. 据我所知,发生这种情况的原因是因为.+字符会无限次匹配直到换行。 But thats the point here. 但这就是重点。 I am at a loss as to why this is happening. 我不知道为什么会这样。 Ideas? 有想法吗?

EDIT: 编辑:

I open a text file and extract content between [ and ]. 我打开一个文本文件,然后在[和]之间提取内容。 Add them to a list. 将它们添加到列表。 Then for each group I try and do the above mentioned matching. 然后,对于每个组,我尝试进行上述匹配。 Now I have tested this by manually entering the string as suggested and it works fine, but for an opened text not so much? 现在,我已经按照建议通过手动输入字符串进行了测试,它可以正常工作,但是对于打开的文本,它不是那么多吗? Can It be that the opened text is messing up the new line? 可能是打开的文本弄乱了新行吗?

 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: See answer. EDIT2:请参阅答案。

Not the most elegant way to go around this I think, but just ended up going though the source line by line and looking up if its a match and if yes, append to the line. 我认为这不是解决问题的最优雅方法,但最终只是逐行通过源代码,然后查找源代码是否匹配,如果匹配,则追加到行中。

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM