2010-11-22 5 views
0

Ich muss Windows-Textdatei analysieren und extrahieren alle Daten im Zusammenhang mit Operationen. Die Operationen werden mit $ OPERATION und $ OPERATION_END getrennt. Was ich tun muss, ist alle Textblöcke für alle Operationen zu extrahieren. Wie kann ich es effektiv mit Regex oder einfache String-Methoden. Ich würde mich freuen, wenn Sie ein kleines Snippet zur Verfügung stellen.Parsing Text mit offenen schließen Tags

$OPERS_LIST 
//some general data 

$OPERATION 
//some text block 
$OPERATION_END 


$OPERS_LIST_END 

Antwort

1

alle Operationen aus der Liste zu erhalten:

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

eine Erweiterungsmethode wie bereits. Übergeben Sie einfach die TextReader, die der Datei entspricht, aus der Sie lesen.

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