[英]String replacement not working as expected
My problem is: 我的问题是:
I have an .ini file that I'm reading as follows: 我有一个.ini文件,如下所示:
StreamReader sr = new StreamReader(txtb_path.Text, Encoding.Default);
StringBuilder content = new StringBuilder();
// schreibt Zeile für Zeile auf den StringBuilder bis das Ende der Datei erreicht ist
while (!sr.EndOfStream)
content.AppendLine(sr.ReadLine());
// StringBuilder als String an die TextBox übergeben
this.textBox1.Text = content.ToString();
Then I apply the following regex: 然后我应用以下正则表达式:
string regex = @"^FensterGemerkt.+?\d+\.\d+\.\d+\,\ \d{2}:\d{2}:\d{2}\ :\ -{1}?\d+\,.*?$"; //@"^Fenster.*$";
RegexOptions options = RegexOptions.Multiline;
// search in
string input = content.ToString();
//txtb_count.Text = "anzahl zeilen: " + Convert.ToString(content.Capacity);
// run regex
MatchCollection matches = Regex.Matches(input, regex, options);
// MessageBox.Show(Convert.ToString(matches.Count));
txtb_count.Text = Convert.ToString(matches.Count);
string cleanup ="";
foreach (Match match in matches)
{
// clean the ini
cleanup = Regex.Replace(input, match.Value, "");
// Output all matches
textBox2.Text = textBox2.Text + "\n" + match.Value;
}
The .ini file looks like this: .ini文件如下所示:
1
FensterGemerkt=12.11.2012, 10:42:37 : -32000,32744--31840,32768
Fenster=-32000,32744,160,24
2
FensterGemerkt=12.11.2012, 10:49:46 : 0,44-1024,768
Fenster=0,44,1024,724
What I want is that if regex matches the first entry: 我想要的是如果正则表达式匹配第一个条目:
FensterGemerkt=12.11.2012, 10:42:37 : -32000,32744--31840,32768
... then replace or remove it. ...然后替换或移除它。
My app works, but only for the last entry in the .ini file. 我的应用程序有效,但仅适用于.ini文件中的最后一个条目。 I think I have a problem in my
foreach
, but I can't figure it out. 我认为我的
foreach
有问题,但我无法解决。
There are better ways to do this but the simplest answer to your problem is because you are resetting cleanup
to always be the replacement of the last value. 有更好的方法来执行此操作,但最简单的答案是因为您将
cleanup
为始终替换为最后一个值。
try 尝试
string cleanup =input;
foreach (Match match in matches)
{
// clean the ini
cleanup = Regex.Replace(cleanup, match.Value, "");
// Output all matches
textBox2.Text = textBox2.Text + "\n" + match.Value;
}
A better solution would be, using Linq: 更好的解决方案是使用Linq:
Regex regex=new Regex(@"^FensterGemerkt.+?\d+\.\d+\.\d+\,\ \d{2}:\d{2}:\d{2}\ :\ -{1}?\d+\,.*?$"; //@"^Fenster.*$",RegexOptions.MultiLine);
string cleanup=regex.Replace(input,string.Empty);
string[] matches=regex.Matches(input).OfType<Match>().Select(m=>m.Value).ToArray();
txtb_count.Text = Convert.ToString(matches.Length);
textBox2.Text = string.Join('\n',matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.