您可以通過幾個步驟解析它。請注意,正則表達式會遺漏字符串和註釋,請小心使用。
首先,我們將使用一個輔助類爲Fields("Target").List = Lists("Value")
行:
class ListData
{
public string Target { get; set; }
public string Value { get; set; }
}
輸出模式:
string patternSelectCase = @"
Select\s+Case\s+Fields\(""(?<CaseField>[\w\s]+)""\)\.Value
(?<Cases>.*?)
End\s+Select
";
string patternCase = @"
Case\s+""(?<Case>[\w\s]+)""\s+
(?:Fields\(""(?<Target>[\w\s]+)""\)\.List\s*=\s*Lists\(""(?<Value>[\w\s]+)""\)\s+)*
";
接下來,我們可以嘗試解析兩遍文本(代碼順便說一句,但是相當基本):
MatchCollection matches = Regex.Matches(vb, patternSelectCase,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace |
RegexOptions.Singleline);
Console.WriteLine(matches.Count);
var data = new Dictionary<String, Dictionary<String, List<ListData>>>();
foreach (Match match in matches)
{
var caseData = new Dictionary<String, List<ListData>>();
string caseField = match.Groups["CaseField"].Value;
string cases = match.Groups["Cases"].Value;
MatchCollection casesMatches = Regex.Matches(cases, patternCase,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace |
RegexOptions.Singleline);
foreach (Match caseMatch in casesMatches)
{
string caseTitle = caseMatch.Groups["Case"].Value;
var targetCaptures = caseMatch.Groups["Target"].Captures.Cast<Capture>();
var valueCaptures = caseMatch.Groups["Value"].Captures.Cast<Capture>();
caseData.Add(caseTitle, targetCaptures.Zip(valueCaptures, (t, v) =>
new ListData
{
Target = t.Value,
Value = v.Value
}).ToList());
}
data.Add(caseField, caseData);
}
現在你有一本包含所有數據的字典。例如:
string s = data["foo"]["Some value2"].First().Value;
這裏有一個工作示例:https://gist.github.com/880148
參見[這個問題](http://stackoverflow.com/questions/1129149/visual-basic-6-0-language-syntax) 。例如,[VBScript語法](http://stackoverflow.com/questions/1129149/visual-basic-6-0-language-syntax/1129425#1129425)和第三方商業[VB6解析器] (http://stackoverflow.com/questions/1129149/visual-basic-6-0-language-syntax/1129163#1129163)。 – MarkJ 2011-03-22 12:08:36