Regex 正则表达式查找包含子字符串A但不包含子字符串B的字符串
我没有看到这个正则表达式问题的精确副本 在Visual Studio 2012中,我需要查找所有具有与特定名称空间匹配的“使用”指令的文件 例如:Regex 正则表达式查找包含子字符串A但不包含子字符串B的字符串,regex,Regex,我没有看到这个正则表达式问题的精确副本 在Visual Studio 2012中,我需要查找所有具有与特定名称空间匹配的“使用”指令的文件 例如: using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; 我想找到所有的“系统”(子字符串A)命名空间引用,但不包括那些包含“集合”(子字符
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
我想找到所有的“系统”(子字符串A)命名空间引用,但不包括那些包含“集合”(子字符串B)的命名空间引用
预期结果:
using System;
using System.Data;
using System.Diagnostics;
似乎是使用正则表达式的好地方。这是似乎有效的最小正则表达式:
^.*System(?!\.Collections).*$
将其分解为若干部分:
^ # from the beginning of the string
.* # match all leading ('using ' in my case)
System # match 'System'
(?!\.Collections) # don't match strings that contain '.Collections'
.*$ #match all (.*) to the end of the line ($)
这种变化:
^.*[ ]System(?!\.Collections).*$
将消除
using my.System.Data;
using mySystem.Diagnostics;
警告:我上一次认真地玩regex大约是20年前,所以我又是一个新手了。。。希望我的解释正确。你需要了解
。零宽度负前瞻(?!…)
(?.零宽度负后向查找
Regex rxFooNotBar = new Regex( @"(?<!bar)Foo(?!Bar)" ) ;
应该这样做。像
这样的字符串应该使用System.Generic.Collections;
通过还是失败?订单重要吗?使用Aardvark.Collections.Management.System;怎么样?使用带有复合词的语句,比如使用SystemManagementCorp.Collections
?是否使用VS find in files(使用regex)util?对于我的具体情况,我正在寻找总是包含Substr A而从不包含Substr B的“使用”语句。Substr B恰好是我们公司的名称空间,因此它将是唯一的。Jerry和Nicholas Carey,它应该失败(我不想在结果中看到这些)@sln,我确实在文件中使用了VS find。那么,使用
与它有什么关系呢?鉴于模式是(?-s),您的正则表达式匹配xxxxxxxxxxxxxxxxxxxx系统yyyyyyyyyyyyyyyyyyyyyyy
,而且,[]已经满足了\b
,所以不需要同时包含这两个(可能只是[])。如果“使用System.something”
是您得到的结果,那么这就是您所拥有的一切。嘿,这是一个临时搜索,无需特别说明。它基本上可以重写为[]System(?!\.Collections)
因为输出中仍然显示完整的行。使用
-最后,什么都没有。在\b
或[]
点上,只需要一行。是的,[]系统(?!\.Collections)
可以工作,但因为子字符串返回一组匹配项,这不是我想要的(尽管由于其他原因很有用)。原始正则表达式在前后都有*
。因此,删去它们绝对没有什么区别,得到的结果是相同的。
Regex rxUsingStatements = new Regex( @"^\s*using\s+System\.(?!Collections)[^; \t]*\s*;" ) ;