【问题标题】:Match any character except '匹配除 ' 之外的任何字符
【发布时间】:2021-01-25 13:58:57
【问题描述】:

我想匹配任何字符(不区分大小写),除非前面是单引号,后跟文本 On Error Goto:

匹配:

on error goto err_handler
if aap = 0 then on error goto Myerrorhandler
    on error goto errorhandler1
   on error goto errorhandler2

不匹配:

' on error goto errorhandler3
'   if aap =0 then on error goto errorhandler4
Any line not containing On Error Goto

我试过了:[^']*(On Error Goto),但没用。

用来测试程序中是否使用了Errorhandler

谢谢!

【问题讨论】:

    标签: regex vba vba7 vba6


    【解决方案1】:

    更新了正则表达式测试用例的链接:https://regex101.com/r/UYll0h/6

    由于' 不存在时不能有字符,因此您需要使用前瞻断言。

    由于在on error goto 之前的行中也可能有代码的其他字符(' 除外)(如在行if aap = 0 then on error goto Myerrorhandler 中),为了处理这些,您还需要设置一个条件检查前瞻后是否存在除' 以外的任何字符。这将由([^']+)? 完成。

    ^(?!')([^']+)?on error goto

    (?) 称为前瞻。它检查其中的字符是否存在。与[] 不同,(?) 即使没有字符也会断言为真。例如,[a] 将检查第一个字符是否为 'a',但它之后的任何表达式将从第二个字符开始检查。另一方面,(?=a) 将检查第一个字符是否为 'a',并且它之后的任何表达式都将从 第一个字符开始检查。换句话说,如果未找到匹配项,前瞻不会将正则表达式引擎移动到下一个字符。

    【讨论】:

      【解决方案2】:

      使用

      ^[^'\n\r]*On Error Goto
      

      使用i 不区分大小写模式和m 多行模式。见proof

      说明

      --------------------------------------------------------------------------------
        ^                        the beginning of the string
      --------------------------------------------------------------------------------
        [^'\n\r]*                any character except: ''', '\n' (newline),
                                 '\r' (carriage return) (0 or more times
                                 (matching the most amount possible))
      --------------------------------------------------------------------------------
        On Error Goto            'On Error Goto'
      

      【讨论】:

      • 对于 vba 不区分大小写是在 .IgnoreCase = True 的正则表达式对象上设置的属性
      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 2023-03-13
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多