2011-08-01 193 views
1

我需要在我的程序中添加功能,以便任何導入的文件都能在addTestingPageContentText方法的「」中找到文本,如下所示。每行上的兩個值將被添加到一個datagridview,它有2列,所以第一列的第一個文本,第二列的第二個文本。我將如何去尋找「sometext」?查找和替換c中的文本#

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

回答

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是相當不錯的一個

+2

小心行開頭的空白。這會拋棄你的'line.StartsWith(「addTestingPageContentText」)'條件。 –

+2

你也可以用'string.IndexOf'替換'for'循環。 –

+0

良好的調用,我認爲空白有一個錯誤從轉換到代碼在帖子中,而不是在數據中。在這種情況下,用string.Trim()修剪空白將是一個很好的起點。 –

0

表達"\"[^"]*\""會發現每...