2011-08-01 95 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

表达"\"[^"]*\""会发现每...