使用正则表达式查找 VBA 条评论

Finding VBA Comments using RegEx

我正在尝试使用正则表达式查找所有 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 中此示例的 link:http://regexr.com/3f24h

出于某种原因,第三个和第四个示例未捕获。问题似乎出在评论中有一个字符串值,我不知道如何解决它。

有什么建议吗?

这应该有效:

("[^"]+"\s)?'.+

此处测试:https://regex101.com/r/dd60QS/1

也许像

^(?:[^"'\n]*("(?:[^"\n]|"")*"))*[^"]*'(.*)$

它处理多个带引号的字符串,以及带引号(双)" 的字符串(我相信这是 VBA 的方式)。

(我保证它在某些情况下会失败,但在大多数情况下可能会起作用;)

Check it out here at regex101.

编辑

添加了一些共产国际的示例并调整了正则表达式。它仍然无法处理 括号中的标识符 (我什至不知道它是什么意思 :S 请参阅最后一行)。但它现在处理他的续行评论。

^(?:[^"'\n]*(?:"(?:[^"\n]|"")*"))*[^']*('(?:_\n|.)*)

Check it out here at regex101.

您无法在 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

这使得识别字符串文字变得困难,尤其是您正在使用 line-by-line 处理:

Debug.Print 42 'The next line... _
"...is not a string literal"

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

Rem old school comment

...也支持续行:

Rem old school comment with line _
continuation.

您可能在想 "that can't be so bad, Rem has to start a line"。如果是,您忘记了语句分隔符 (:)...

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 使用的语法高亮显示 甚至无法捕获所有这些奇怪的极端情况。