Car*_*ngo 7 regex negative-lookahead regex-lookarounds
我正在做一些正规表达体操.我为自己设置了尝试搜索C#代码的任务,其中使用了as-operator而没有在合理的空间内进行空检查.现在我不想解析C#代码.例如,我想捕获诸如的代码片段
    var x1 = x as SimpleRes;
    var y1 = y as SimpleRes;
    if(x1.a == y1.a)
但是,没有捕获
    var x1 = x as SimpleRes;
    var y1 = y as SimpleRes;
    if(x1 == null)
也不是那件事
    var x1 = x as SimpleRes;
    var y1 = y as SimpleRes;
    if(somethingunrelated == null) {...}
    if(x1.a == y1.a)
因此,任何随机的空检查都将被视为"良好检查",因此未被发现.
问题是:我如何匹配某些东西,同时确保在其周围环境中找不到其他东西.
我尝试过天真的方法,寻找'as'然后在150个字符内做一个负面的预测.
\bas\b.{1,150}(?!\b==\s*null\b)
上述正则表达式与所有上述示例相匹配.我的直觉告诉我,问题是前瞻然后做负面预测会发现许多情况,即前瞻没有找到'== null'.
如果我尝试否定整个表达式,那么这也无济于事,因为这将匹配大多数C#代码.
rid*_*ner 11
我喜欢正则表演体操!这是一个注释的PHP正则表达式:
$re = '/# Find all AS, (but not preceding a XX == null).
    \bas\b               # Match "as"
    (?=                  # But only if...
      (?:                # there exist from 1-150
        [\S\s]           # chars, each of which
        (?!==\s*null)    # are NOT preceding "=NULL"
      ){1,150}?          # (and do this lazily)
      (?:                # We are done when either
        (?=              # we have reached
          ==\s*(?!null)  # a non NULL conditional
        )                #
      | $                # or the end of string.
      )
    )/ix'
这里是Javascript风格:
re = /\bas\b(?=(?:[\S\s](?!==\s*null)){1,150}?(?:(?===\s*(?!null))|$))/ig;
这个确实让我头疼了一点......
这是我正在使用的测试数据:
text = r"""    var x1 = x as SimpleRes;
    var y1 = y as SimpleRes;
    if(x1.a == y1.a)
however, not capture
    var x1 = x as SimpleRes;
    var y1 = y as SimpleRes;
    if(x1 == null)
nor for that matter
    var x1 = x as SimpleRes;
    var y1 = y as SimpleRes;
    if(somethingunrelated == null) {...}
    if(x1.a == y1.a)"""