搜索确切的字符串或跳过包含字符串的行

时间:2017-02-06 10:13:03

标签: c#

我是C#的新手,我遇到一个问题,当我搜索字符串"code:A1"时,它也会给出包含"code:A14"的行。我想从代码中搜索确切的单词"code:A1"或禁止"code:A14"。这就是我所做的,但它不起作用:

try
{
    using (System.IO.StreamReader file = new System.IO.StreamReader(@"<path to file>"))
    {
        string motcletest = "code:A1";
        string motcle = "code:A16";
        string motcledm = "code:A14";
        string line;

        line = file.ReadLine();
        do
        {
            if (line.Contains(motcletest) || line.Contains(motcle))
            {
                SetupV02_textbox.Text = line;
            }
            if (line.Contains(motcledm))
            {
                continue;
            }
        }
        while ((line = file.ReadLine()) != null);

        //string retval = SetupV02_textbox.Text.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First(p => p.Equals(motcle));
        string setup = SetupV02_textbox.Text;
        string testomada2 = setup.Split(new string[] { "code:" }, StringSplitOptions.None).Last();
        label2.Text = testomada2.ToString();
    }
}    

2 个答案:

答案 0 :(得分:0)

为了使其正确,您应该发布文本文件的内容。 无论如何,您可以使用以下内容禁止code:A14并仅选择code:A16code:A1

if ((linee.Contains(motcletest) || linee.Contains(motcle)) && (!linee.Contains(motcledm)))
{
    SetupV02_textbox.Text = linee;
}

答案 1 :(得分:0)

如果你想要完全相同的值并且行中没有额外的内容,你可以使用equals,

linee.Equals( “代码:A1”)