在c#中查找和替换文本

时间:2011-08-01 12:40:15

标签: c# regex import find

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

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

2 个答案:

答案 0 :(得分:1)

既不快也不高效,但对正则表达式的新手更容易理解:

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);
    }
}

但是我会认真地推荐在互联网上浏览一些很棒的教程。 This是一个非常好的

答案 1 :(得分:0)

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