0

我需要解析 Windows 文本文件并提取与操作相关的所有数据。操作由 $OPERATION 和 $OPERATION_END 分隔。我需要做的是提取所有操作的所有文本块。如何使用正则表达式或简单的字符串方法有效地做到这一点。感谢您提供小片段。

$OPERS_LIST
//some general data

$OPERATION
//some text block
$OPERATION_END


$OPERS_LIST_END
4

3 回答 3

1

从列表中获取所有操作:

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...
}
于 2010-11-22T14:41:48.127 回答
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
}
于 2010-11-22T14:36:41.063 回答
1

尝试这样的扩展方法。只需传入TextReader与您正在读取的文件相对应的 。

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.");
}
于 2010-11-22T14:37:55.913 回答