正则表达式 – 正则表达式负向前瞻
发布时间:2020-12-14 06:24:25 所属栏目:百科 来源:网络整理
导读:我正在做一些正规表达体操.我为自己设置了尝试搜索C#代码的任务,其中使用了as-operator而没有在合理的空间内进行空检查.现在我不想解析C#代码.例如.我想捕获诸如的代码片段 var x1 = x as SimpleRes; var y1 = y as SimpleRes; if(x1.a == y1.a) 但是,没有捕
我正在做一些正规表达体操.我为自己设置了尝试搜索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个字符内做一个负面的预测. basb.{1,150}(?!b==s*nullb) 上述正则表达式与所有上述示例匹配.我的直觉告诉我,问题是前瞻然后做负面预测会发现许多情况,即前瞻没有找到’== null’. 如果我尝试否定整个表达式,那么这也无济于事,因为这将匹配大多数C#代码.
我喜欢正则表达式体操!这是一个注释的PHP正则表达式:
$re = '/# Find all AS,(but not preceding a XX == null). basb # Match "as" (?= # But only if... (?: # there exist from 1-150 [Ss] # 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 = /basb(?=(?:[Ss](?!==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)""" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |