2010-11-22 46 views
0

J'ai besoin d'analyser le fichier texte Windows et d'extraire toutes les données liées aux opérations. Les opérations sont séparées par $ OPERATION et $ OPERATION_END. Ce que je dois faire est d'extraire tous les blocs de texte pour toutes les opérations. Comment puis-je le faire efficacement en utilisant des méthodes regex ou String simples. J'apprécierais que vous fournissiez un petit extrait.Analyse du texte avec des balises de fermeture ouvertes

$OPERS_LIST 
//some general data 

$OPERATION 
//some text block 
$OPERATION_END 


$OPERS_LIST_END 

Répondre

1

pour obtenir toutes les opérations de la liste:

var input = @"$OPERS_LIST 
//some general data 

$OPERATION 

erfgergwerg 
ewrg//some text block 

$OPERATION_END 

$OPERATION 
//some text block 
$OPERATION_END 


$OPERATION 
//some text block 
$OPERATION_END 


$OPERS_LIST_END"; 
foreach (Match match in Regex.Matches(input, @"(?s)\$OPERATION(?<op>.+?)\$OPERATION_END")) 
{ 
var operation = match.Groups["op"].Value; 

// do something with operation... 
} 
1
try { 
    if (Regex.IsMatch(subjectString, @"\$OPERATION(.*?)\$OPERATION_END", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)) { 
     // Successful match 
    } else { 
     // Match attempt failed 
    } 
} catch (ArgumentException ex) { 
    // Syntax error in the regular expression 
} 
1

Essayez une méthode d'extension comme celui-ci. Passez juste le TextReader qui correspond au fichier que vous lisez.

public static IEnumerable<string> ReadOperationsFrom(this TextReader reader) 
{ 
    if (reader == null) 
     throw new ArgumentNullException("reader"); 

    string line; 
    bool inOperation = false; 

    var buffer = new StringBuilder(); 

    while ((line = reader.ReadLine()) != null) { 
     if (inOperation) { 
      if (line == "$OPERATION") 
       throw new InvalidDataException("Illegally nested operation block."); 

      if (line == "$OPERATION_END") { 
       yield return buffer.ToString(); 

       buffer.Length = 0; 
       inOperation = false; 
      } else { 
       buffer.AppendLine(line); 
      } 
     } else if (line == "$OPERATION") { 
      inOperation = true; 
     } 
    } 

    if (inOperation) 
     throw new InvalidDataException("Unterminated operation block."); 
}