我试图使用正则表达式查找所有VBA注释.我有一些主要有用的东西,但有一些我无法弄清楚的例外.
我正在使用的表达式:
'(?!.*").*
拿我们的测试代码:
Working - This is a test 'This should be captured Working - "this is a test" 'This should be captured Not Working - "this is a test" 'This should be "captured" Not Working - This is a test 'This should be "captured" Working - "this is a test 'this should not capture'" 'this should capture Working - "this isn't a test" 'this should capture
以下是RegExr中此示例的链接:http: //regexr.com/3f24h
由于某种原因,第三和第四个例子没有捕获.问题似乎是在评论中有一个字符串值,我无法弄清楚如何解决它.
有什么建议?
你无法在VBA代码中找到所有注释(更不用说字符串文字)和正则表达式 - 句点.相信我,我在Rubberduck的Smart Indenter模块工作期间尝试过(如果不够明确 - 完全披露,我是贡献者).您需要实际解析代码.您将遇到的第一个问题是续行:
'Comment with a line _ continuation Debug.Print 'End of line comment _ with line continuation. Debug.Print 'Multiple line continuation operators _ _ still work. Debug.Print 'This is actually *not* a line continuation_ Debug.Print 42
这使得识别字符串文字很困难,尤其是您使用逐行处理:
Debug.Print 42 'The next line... _ "...is not a string literal"
您还必须处理旧的Rem
注释语法...
Rem old school comment
......也支持线路延续:
Rem old school comment with line _ continuation.
你可能会想"不可能这么糟糕,Rem必须开始行".如果你是,你忘记了语句分隔符(:
)...
Debug.Print 42: Rem statement separator comment.
...或其邪恶的双胞胎语句分隔符与行继续结合:
Debug.Print 42: Rem this can be _ continued too.
你解决了一些问题,包括整理字符串文字和这些评论......
Debug.Print "Unmatched double quotes." 'Comment" Debug.Print "Interleaved single 'n double quotes." 'Comment"
...但是像这种野兽的括号标识符(由@ThunderFrame提供)呢?
'No comments or strings in the line below. Debug.Print [Evil:""Comment"'here]
请注意,SO使用的语法高亮显示甚至没有捕获所有这些奇怪的角落情况.