打印处理文件后跟<id> </id>

时间:2013-05-10 00:52:43

标签: c# string

private void button1_Click(object sender, EventArgs e)
{
    string value = textBox1.Text;
    string[] lines = value.Split(Environment.NewLine.ToCharArray()); 
    foreach (string l in lines)
    if (l.IndexOf("Processing")==0)
    {
       textBox4.Text = textBox4.Text + l + Environment.NewLine;
    }

    MatchCollection matches2 = Regex.Matches(value, "\"([^\"]*)\"");
    foreach (Match match2 in matches2)
    {
        foreach (Capture capture2 in match2.Captures)
        {              
            textBox4.Text = textBox4.Text + Environment.NewLine + capture2.Value;   

        }
    }
}   

我的输入是: -

Processing \\Users\\bhargava\\Desktop\New.txt

<"dfgsgfsgfsgfsgfsgfsgfs">

Processing \\Users\\bhargava\\Desktop\\New.txt

<"dfgsgfsgfsgfsgfsgfsgfs">

Processing \\Users\\bhargava\\Desktop\New.txt

Processing \\Users\\bhargava\\Desktop\\New.txt

我需要输出: -

Processing \\Users\\bhargava\\Desktop\New.txt

"dfgsgfsgfsgfsgfsgfsgfs"

Processing \\Users\\bhargava\\Desktop\\New.txt

"dfgsgfsgfsgfsgfsgfsgfs"

Processing \\Users\\bhargava\\Desktop\New.txt

Processing \\Users\\bhargava\\Desktop\\New.txt

我得到了: -

Processing \\Users\\bhargava\\Desktop\New.txt


Processing \\Users\\bhargava\\Desktop\\New.txt


Processing \\Users\\bhargava\\Desktop\New.txt

Processing \\Users\\bhargava\\Desktop\\New.txt

"dfgsgfsgfsgfsgfsgfsgfs"

"dfgsgfsgfsgfsgfsgfsgfs"

请帮帮我!

1 个答案:

答案 0 :(得分:0)

您的代码中缺少一对花括号。第一个foreach需要花括号来封装之后出现的所有代码。如果没有它,它只会抓住下一个语句并为每个行元素重复它。这就是为什么你得到的每一行以“Processing”开头,然后是你ID的两个匹配。试试这个:

private void button1_Click(object sender, EventArgs e)
{
        string[] lines = value.Split(Environment.NewLine.ToCharArray()); 
        foreach (string l in lines)
        {
            if (l.IndexOf("Processing")==0)
            {
               textBox4.Text = textBox4.Text + l + Environment.NewLine;
            }

            MatchCollection matches2 = Regex.Matches(l, "\"([^\"]*)\"");
            foreach (Match match2 in matches2)
            {
                foreach (Capture capture2 in match2.Captures)
                {              
                    textBox4.Text = textBox4.Text + Environment.NewLine + capture2.Value;   

                }
            }
        }
    }   

所以在这个例子中我添加了我提到的花括号,我也摆脱了value,而是告诉正则表达式搜索当前行。如果您每次最终都会搜索值,那么ID的重复次数将超出您所需的输出值。