2014-02-21 76 views
0

我没有看到这个表达式问题完全相同的副本...正则表达式查找包含子弦乐但不包含子乙

在Visual Studio 2012,我需要找到的所有文件与“使用”指令匹配特定的名称空间。

例子:

using System; 
    using System.Collections; 
    using System.Collections.Generic; 
    using  System.Data; 
    using System.Diagnostics; 

我想找到所有的 '系统' 除包含 '集合'(串B)的(子A)命名空间引用。

期望的结果:

using System; 
    using  System.Data; 
    using System.Diagnostics; 

似乎想使用正则表达式的好地方。

+0

像'使用System.Generic.Collections;'通过或失败的字符串? – Jerry

+0

命令重要吗?怎么样“使用Aardvark.Collections.Management.System;'。如何使用'using'语句来处理像'using SystemManagementCorp.Collections'这样的复合词? –

+0

你是否在文件中使用VS查找(使用正则表达式)util? – sln

回答

0

这是一个似乎工作的最小的正则表达式:

^.*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; 

Related question #1

Related question #2

Rubular: A nice online regex utility

警告:我最后正则有认真玩大约20年前,所以我又是新手...希望我得到的解释权。

+1

那么,“使用”与它有什么关系?由于模式是(?-s),所以你的正则表达式匹配'XXXXXXXXXXXXXXXXXXXXXX SystemYYYYYYYYYYYYYYYYYYYYY'此外,[]已经满足'\ b',所以不需要同时包含这两个(可能只是[])。如果“使用System.something”是你得到的结果,那么就是你所拥有的。嘿,它是一个临时搜索,不需要具体说明。 – sln

+1

它基本上可以被重写为'[] System(?!\ Collections)',因为无论如何都会在输出中显示完整的行。 – sln

+0

'使用' - 最后,什么都没有。在'\ b'或'[]'点上是,只需要一个。是的,'[] System(?!\ Collections)'可以工作,但是由于子字符串返回了一堆我不在寻找的匹配(尽管其他原因很有用)。 – mobill

0

您需要了解

  • (?!...)。零宽度负向预测。
  • (?<!...)。零宽度负回顾后

正则表达式

Regex rxFooNotBar = new Regex(@"(?<!bar)Foo(?!Bar)") ; 

将匹配包含“foo”的字符串,而不是“酒吧”。

对于您的具体情况—找到引用System命名空间没有“收藏”作为一个孩子的命名空间using声明,这应该做的伎俩:

Regex rxUsingStatements = new Regex(@"^\s*using\s+System\.(?!Collections)[^; \t]*\s*;") ; 

应该做你。

+1

这是...... [某种程度上错误](http://regex101.com/r/jB8bH3)。 – Jerry

+0

匹配“arFoooBar”。 – sln

相关问题