使用RegEx查找VBA注释

1 regex vba comments

我试图使用正则表达式查找所有VBA注释.我有一些主要有用的东西,但有一些我无法弄清楚的例外.

我正在使用的表达式:

'(?!.*").*
Run Code Online (Sandbox Code Playgroud)

拿我们的测试代码:

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
Run Code Online (Sandbox Code Playgroud)

以下是RegExr中此示例的链接:http: //regexr.com/3f24h

由于某种原因,第三和第四个例子没有捕获.问题似乎是在评论中有一个字符串值,我无法弄清楚如何解决它.

有什么建议?

Com*_*ern 5

你无法在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
Run Code Online (Sandbox Code Playgroud)

这使得识别字符串文字很困难,尤其是您使用逐行处理:

Debug.Print 42 'The next line... _
"...is not a string literal"
Run Code Online (Sandbox Code Playgroud)

您还必须处理旧的Rem注释语法...

Rem old school comment
Run Code Online (Sandbox Code Playgroud)

......也支持线路延续:

Rem old school comment with line _
continuation.
Run Code Online (Sandbox Code Playgroud)

你可能会想"不可能这么糟糕,Rem必须开始行".如果你是,你忘记了语句分隔符(:)...

Debug.Print 42: Rem statement separator comment.
Run Code Online (Sandbox Code Playgroud)

...或其邪恶的双胞胎语句分隔符与行继续结合:

Debug.Print 42: Rem this can be _
continued too.
Run Code Online (Sandbox Code Playgroud)

你解决了一些问题,包括整理字符串文字和这些评论......

Debug.Print "Unmatched double quotes." 'Comment"
Debug.Print "Interleaved single 'n double quotes." 'Comment"
Run Code Online (Sandbox Code Playgroud)

...但是像这种野兽的括号标识符(由@ThunderFrame提供)呢?

'No comments or strings in the line below.
Debug.Print [Evil:""Comment"'here] 
Run Code Online (Sandbox Code Playgroud)

请注意,SO使用语法高亮显示甚至没有捕获所有这些奇怪的角落情况.

  • @Vityata - 在Excel中,它被视为表达式(因此您可以将其用于命名范围).它也可以用作COM成员调用 - 即`ws.[_ CheckSpelling]`.我怀疑你在COM中遇到包含引号的成员名称的任何东西,但它可能是可行的,因为对象可以自由地实现`GetIDsOfNames`,但是他们想要. (3认同)
  • @Vityata - VBE语法高亮显示器不使用正则表达式 - 它解析代码. (2认同)