0
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"

请帮帮我!

4

1 回答 1

0

您的代码中缺少一对花括号。第一个 foreach 需要花括号来封装后面的所有代码。没有它,它只会抓取下一条语句并为行的每个元素重复它。这就是为什么您会得到以“处理”开头的每一行,然后是您的 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。

于 2013-05-10T02:32:41.290 回答