2011-08-01 5 views
1

Je dois ajouter des fonctionnalités dans mon programme pour que tout fichier importé trouve le texte dans le "" de la méthode addTestingPageContentText comme indiqué ci-dessous. Les deux valeurs sur chaque ligne seront ensuite ajoutées à un DataGridView qui a 2 colonnes donc le premier texte dans la première colonne puis le deuxième dans la 2ème colonne. Comment irais-je Trouver le "sometext"?Recherche et remplacement de texte dans C#

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

Répondre

1

Ni rapide ni efficace, mais il est plus facile de comprendre pour les nouveaux expressions régulières:

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

Cependant, je recommande sérieusement d'aller grâce à certains des grands tutoriels sur Internet. This est plutôt bon

+2

Attention aux espaces blancs au début de la ligne. Cela mettra hors de votre 'line.StartsWith (" addTestingPageContentText ")' condition. –

+2

Vous pouvez également remplacer ces boucles 'for' par' string.IndexOf'. –

+0

Bon appel, j'ai supposé les espaces il y avait une erreur de la conversion en code dans le message, pas dans les données. Dans ce cas, couper les espaces avec string.Trim() serait un bon point de départ. –

0

L'expression "\"[^"]*\"" trouverait chaque ...

Questions connexes