繁体   English   中英

在C#中查找和替换文本

[英]Finding and replacing text in c#

我需要在程序中添加功能,以便导入的任何文件都可以在addTestingPageContentText方法的“”中找到文本,如下所示。 然后将每行上的两个值添加到具有2列的datagridview中,因此第一个文本在第一列中,然后第二个在第二列中。 我将如何查找“ sometext”?

    addTestingPageContentText("Sometext", "Sometext");
    addTestingPageContentText("Sometext2", "Sometext2");
... continues n number of times.

既不快速也不高效,但是对于那些新的正则表达式来说更容易理解:

while (!endOfFile)
{
    //get the next line of the file
    string line = file.readLine();

    EDIT: //Trim WhiteSpaces at start
    line = line.Trim();
    //check for your string
    if (line.StartsWith("addTestingPageContentText"))
    {
        int start1;
        int start2;
        //get the first something by finding a "
        for (start1 = 0; start1 < line.Length; start1++)
        {
            if (line.Substring(start1, 1) == '"'.ToString())
            {
                start1++;
                break;
            }
        }
        //get the end of the first something
        for (start2 = start1; start2 < line.Length; start2++)
        {
            if (line.Substring(start2, 1) == '"'.ToString())
            {
              start2--;
              break;
            }
        }
        string sometext1 = line.Substring(start1, start2 - start1);
        //get the second something by finding a "
        for (start1 = start2 + 2; start1 < line.Length; start1++)
        {
            if (line.Substring(start1, 1) == '"'.ToString())
            {
                start1++;
                break;
            }
        }
        //get the end of the second something
        for (start2 = start1; start2 < line.Length; start2++)
        {
            if (line.Substring(start2, 1) == '"'.ToString())
            {
                start2--;
                break;
            }
        }
        string sometext2 = line.Substring(start1, start2 - start1);
    }
}

但是,我强烈建议您浏览互联网上的一些很棒的教程。 是一个很好的

表达式"\\"[^"]*\\""将找到每个...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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