2013-03-02 85 views
3

我需要能夠匹配正則表達式:正則表達式混合情況下排除特定情況下

  • 一個)所有除幾個特定字的較低/上層例
  • b)中組合某些病例組合。

我必須搜索bash通數以千計的源代碼文件,誤拼寫變量的出現。

具體來說,我尋找的字是FrontEnd這在我們的編碼風格指南可以在根據上下文2種方式究竟寫:

FrontEnd (F and E upper) 
frontend (all lower) 

所以我需要「追趕」的任何出現次數不遵守我們的編碼標準爲:

frontEnd 
FRONTEND 
fRonTenD 

我一直在閱讀正則表達式的很多教程這個具體的例子,我無法找到一種方法,說:「與此模式匹配,但不匹配,如果正是這樣一個或另一個「。

我想它會類似於嘗試匹配「000000到999999之間的任何數字,除了確切的數字555555或數字123456」,我想邏輯是類似的(當然,我不打結這樣做要麼:))

日Thnx


附加註釋:

我不能用grep管道輸送到grep -v,因爲我可能會錯過線;例如,如果我這樣做:

grep -i frontend | grep -v FrontEnd | grep -v frontend 

會錯過這樣一行:

if(frontEnd.name == 'hello' || FrontEnd.value == 3) 

因爲第二occurence將隱藏的整條生產線。因此,我正在尋找一個正則表達式來與egrep一起使用,以完成我需要的完全匹配。

回答

1

您將無法與egrep做到這一點很容易,因爲它不」 t支持lookaheads。用perl來做這個可能是最簡單的。

perl -ne 'print if /(?!frontend|FrontEnd)(?i)frontend/;' 

在使用時只需管文通過stdin

這是如何工作:

perl -ne 'print if /(?!frontend|FrontEnd)(?i)frontend/;' 
^  ^^^ ^^^^    ^^The pattern that matches both the correct and incorrect versions. 
|  || |  | | | |     | This switch turns on case insensitive matching for the rest of the regular expression (use (?-i) to turn it off) (perl specific) 
|  || |  | | | | The pattern that match the correct versions. 
|  || |  | | | Negative forward look ahead, ensures that the good stuff won't be matched 
|  || |  | | Begin regular expression match, returns true if match 
|  || |  | Begin if statement, this expression uses perl's reverse if semantics (expression1 if expression2;) 
|  || | Print content of $_, which is piped in by -n flag 
|  || Evaluate perl code from command line 
|  | Wrap code in while (<>) { } takes each line from stdin and puts it in $_ 
| Perl command, love it or hate it. 
+0

就像一個魅力!這完全是我需要的。 Thanx OmnipotentEntity。特別是我在'find -exec'中使用了它,並將'{}'傳遞給了perl,因此它可以在數千個文件中「檢測」這些奇點。 – 2013-03-04 13:03:19

0

這真的應該是一個評論,但是有什麼理由不能使用sed?我想這樣

sed 's/frontend/FrontEnd/ig' input.txt 

那是當然,假設你想要糾正不正常的版本...

+0

這是行不通的,因爲'frontend'是有效的爲好。 – OmnipotentEntity 2013-03-02 02:26:32

+0

有一個原因:「好版本」'FrontEnd'或'frontend'是不可互換的,它取決於上下文。因此,我們不能將「所有出現的拼寫錯誤」替換爲「FrontEnd」(因爲「sed」會這樣做),因爲有些應該轉換爲「FrontEnd」,而其他人應該讀取「前端」。我們正在尋求一種方法來在屏幕上顯示這些手動選擇正確的替代品。 – 2013-03-02 02:29:31

+0

我知道,但我認爲「有效」意味着寫入的方式並不重要。噢,值得一試;我只是試圖迴避這個問題,真的。也許有人可以把這個答案變成評論? – jja 2013-03-02 02:32:02