代码之家  ›  专栏  ›  技术社区  ›  Morgan

匹配前面没有引号的模式

  •  0
  • Morgan  · 技术社区  · 7 年前

    我有这个图案 (?<!')(\w*)\((\d+|\w+|.*,*)\) 这是为了匹配字符串,比如:

    • c(4)
    • hello(54, 41)

    在对so的一些回答之后,我添加了一个负lookbehind,以便如果输入字符串前面有 ' ,字符串根本不应该匹配。但是,它仍然部分匹配。

    例如:

    'c(4) 收益率 (4) 尽管它不应该匹配任何东西,因为后面是负面的。

    如果字符串前面有 没有匹配的?

    1 回复  |  直到 7 年前
        1
  •  1
  •   user557597    7 年前

    既然没人来,我就把这个扔掉让你开始。

    这个正则表达式将匹配如下内容

    aa(a , sd,,,f,)
    aa( as , " ()asdf)) " ,, df, , )
    asdf()

    但不是

    'ab(s)

    这将解决基本问题 (?<!['\w])\w*
    在哪里? (?<!['\w]) 不会让引擎跳过一个字符
    为了满足 不引用 .
    那么可选的词 \w* 抓住所有的字眼。
    如果是 'aaa( 引用在前面,然后就不匹配了。

    这里的regex修饰了我认为你要完成的任务
    在正则表达式的函数体部分。
    一开始可能有点难以理解。

    (?s)(?<!['\w])(\w*)\(((?:,*(?&variable)(?:,+(?&variable))*[,\s]*)?)\)(?(DEFINE)(?<variable>(?:\s*(?:"[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')\s*|[^()"',]+)))

    可读版本(通过: http://www.regexformat.com )

     (?s)                          # Dot-all modifier
    
     (?<! ['\w] )                  # Not a quote, nor word behind
                                   # <- This will force matching a complete function name
                                   #    if it exists, thereby blocking a preceding quote '
    
     ( \w* )                       # (1), Function name (optional)
     \(
     (                             # (2 start), Function body
          (?:                           # Parameters (optional)
               ,*                            # Comma (optional)
               (?&variable)                  # Function call, get first variable (required)
               (?:                           # More variables (optional)
                    ,+                            # Comma  (required)
                    (?&variable)                  # Variable (required)
               )*
               [,\s]*                        # Whitespace or comma (optional)
          )?                            # End parameters (optional)
     )                             # (2 end)
     \)
    
     # Function definitions
     (?(DEFINE)
          (?<variable>                  # (3 start), Function for a single Variable
               (?:
                    \s* 
                    (?:                           # Double or single quoted string
                         "                            
                         [^"\\]* 
                         (?: \\ . [^"\\]* )*
                         "
                      |  
                         '                      
                         [^'\\]* 
                         (?: \\ . [^'\\]* )*
                         '
                    )
                    \s*     
                 |                              # or,
                    [^()"',]+                     # Not quote, paren, comma (can be whitespace)
               )
          )                             # (3 end)
     )