2014-02-21 78 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

相關問題