正则表达式 – 正则表达式负向前瞻

我正在做一些正规表达体操.我为自己设置了尝试搜索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#代码.

我喜欢正则表达式体操!这是一个注释的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)"""

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...