我正在尝试编写一个VBA解析器,为了创建一个
这些工作得非常好:
显然,这两个问题都是由于
我想知道是否可能使用正则表达式解决问题#1,考虑到值可能是包含撇号和可能包含转义(双倍)双引号的字符串。
我认为我可以在
我是说,我可以在这里实现一些附加逻辑,以执行正则表达式无法完成的任务。
如果问题#1可以使用正则表达式解决,那么我相信问题#2也可以...我在正确的轨道上吗?我应该放弃[相当复杂]的正则表达式模式,考虑另一种方法吗?我对贪婪子表达式、反向引用和其他更高级的正则表达式特性不太熟悉 - 这是限制我的因素,还是只是我用错了工具?
注:模式可能匹配非法语法 - 这段代码仅针对可编译的VBA代码运行。
ConstantNode
,我需要能够匹配所有可能的Const
声明变化。这些工作得非常好:
Const foo = 123
Const foo$ = "123"
Const foo As String = "123"
Private Const foo = 123
Public Const foo As Integer = 123
Global Const foo% = 123
If there's a comment at the end of the declaration, I'm picking it up as part of the value:
Const foo = 123 'this comment is included as part of the value
If there's two or more constants declared in the same instruction, I'm failing to match the entire instruction:
Const foo = 123, bar = 456
这是我正在使用的正则表达式:
/// <summary>
/// Gets a regular expression pattern for matching a constant declaration.
/// </summary>
/// <remarks>
/// Constants declared in class modules may only be <c>Private</c>.
/// Constants declared at procedure scope cannot have an access modifier.
/// </remarks>
public static string GetConstantDeclarationSyntax()
{
return @"^((Private|Public|Global)\s)?Const\s(?<identifier>[a-zA-Z][a-zA-Z0-9_]*)(?<specifier>[%&@!#$])?(?<as>\sAs\s(?<reference>(((?<library>[a-zA-Z][a-zA-Z0-9_]*))\.)?(?<identifier>[a-zA-Z][a-zA-Z0-9_]*)))?\s\=\s(?<value>.*)$";
}
显然,这两个问题都是由于
(?<value>.*)$
部分引起的,该部分匹配直到行尾的任何内容。我通过将整个模式括在一个捕获组中并添加一个可选逗号,使VariableNode
支持一条指令中的多个声明,但由于常量具有此value
组,因此这样做会导致第一个常量将所有后续声明都捕获为其值的一部分......这让我回到了问题#1。我想知道是否可能使用正则表达式解决问题#1,考虑到值可能是包含撇号和可能包含转义(双倍)双引号的字符串。
我认为我可以在
ConstantNode
类本身中解决它,在Value
的getter中:/// <summary>
/// Gets the constant's value. Strings include delimiting quotes.
/// </summary>
public string Value
{
get
{
return RegexMatch.Groups["value"].Value;
}
}
我是说,我可以在这里实现一些附加逻辑,以执行正则表达式无法完成的任务。
如果问题#1可以使用正则表达式解决,那么我相信问题#2也可以...我在正确的轨道上吗?我应该放弃[相当复杂]的正则表达式模式,考虑另一种方法吗?我对贪婪子表达式、反向引用和其他更高级的正则表达式特性不太熟悉 - 这是限制我的因素,还是只是我用错了工具?
注:模式可能匹配非法语法 - 这段代码仅针对可编译的VBA代码运行。