繁体   English   中英

解析.NET中的VB6代码

[英]parsing VB6 code in .NET

我有一个用C#编写的WPF项目,为了获得有关外部依赖项的一些信息,我需要解析一个VB6脚本。 脚本的位置发生了变化,其内容发生了一些变化,但我感兴趣的主要代码的格式如下:

Select Case Fields("blah").Value
    Case "Some value"
        Fields("other blah").List = Lists("a list name")
    ...
End Select

我需要从中提取出当字段'blah'设置为'某个值'时,字段'other blah'的列表会更改为列出'列表名'。 我尝试使用谷歌搜索作为.NET库编写的VB6解析器,但还没有找到任何东西。 有可能得到像这样的答案,我应该只使用正则表达式在VB6脚本中找到这样的代码,并提取我需要的数据吗? 代码可以在子程序中找到,这样我就无法传递'blah','some value'并返回'other blah','list name'。 我无法控制这个VB6脚本的内容。

您可以通过几个步骤解析它。 请注意正则表达式错过字符串和注释,因此请小心使用。

首先,我们将为Fields("Target").List = Lists("Value")使用辅助类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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM