2012-12-17 50 views
0

在我的Java文件中有分配給Java字符串像很多SQL查詢的查詢:我想找到所有的(多)「SELECT ...」不包含特定字詞

/* ... */ 
String str1 = "SELECT item1, item2 from table1 where this=that and MYWORD=that2 and this3=that3"; 
/* ... */ 
String str2 = "SELECT item1, item2 from table1 where this=that and" + 
       " MYWORD=that2 and this3=that3 and this4=that4"; 
/* ... */ 
/* ... */ 
String str3 = "SELECT item1, item2 from table2 where this=that and this2=that2 and" + 
       " this3=that3 and this4=that4"; 
/* ... */ 
String str4 = "SELECT item1, item2 from table3 where this=that and MYWORD=that2" + 
       " and this3=that3 and this4=that4"; 
/* ... */ 
String str5 = "SELECT item1, item2 from table4 where this=that and this2=that2 and this3=that3"; 
/* ... */ 

現在找出在其中不包含「MYWORD」單詞的「SELECT ...」查詢

從我之前的一個S/O問題中,我得到了answer how to find all the 'SELECT...' queries,但我需要擴展該解決方案以找到不包含某個單詞的解決方案。

我已經試過正則表達式SELECT(?!.*MYWORD).*;無法找到多查詢(如STR3以上),發現只有一行的。

我也試過正則表達式SELECT[\s\S]*?(?!MYWORD).*(?<=;)$找到所有的查詢,並且無法確定單詞'MYWORD'是否存在於查詢中。

我知道我非常接近解決方案,仍然無法弄清楚。 任何人都可以幫助我嗎? (我在窗戶上使用記事本++)

+0

可以有永遠在你的字符串中逃脫了引號?像「\」2 \「由4 \」board「'? –

回答

3

第一個正則表達式的問題是.與換行符不匹配。在正常的正則表達式中,有一個選項可以改變它,但我不知道該功能是否存在於記事本++中。

與第二個正則表達式的問題是匹配「選擇,然後一些東西,然後任何不匹配MYWORD,然後更多的東西,然後一個分號」即使MYWORD存在,正則表達式引擎將愉快地匹配(?!MYWORD)到不是MYWORD的字符串的其他部分。

像這樣的東西應該工作(警告:在記事本中沒有測試++):

SELECT(?![^;]*MYWORD)[^;]*; 

相反的.,匹配任何不是一個分號。這應該允許你匹配一個換行符。

除此之外,同樣重要的是不允許分號參與匹配。否則,該模式可能會擴大以吞噬多個SELECT語句,因爲它會嘗試匹配。

+0

+1,我首先想到「如果你的'SELECT'語句裏面有分號怎麼辦?」,但是它們在那裏看起來不合法,所以這種方法可能就好了。 –

+0

@TimPietzcker,從技術上講,一個強大的解決方案將需要Java和SQL的全面解析!例如,您可以在select語句的字符串中使用轉義分號,或者在Java註釋中使用「SELECT」字樣。但我認爲我們可以爲文本編輯器的正則表達式設置一個較低的欄。 – dan1111

+0

非常感謝。它的工作和我預期的完全一樣!我只需要在'SELECT'後添加一個額外的空格以避免匹配java語句,如:'boolean isSelected = 1;' –

1

試試這個(關於使用Perl兼容的正則表達式記事本++的當前版本,舊版本不支持多行正則表達式):

SELECT (?:(?!MYWORD)[^"]|"\s*\+\s*")*"\s*; 

說明:

SELECT  # Match SELECT 
(?:   # Match either... 
(?!MYWORD) # (as long as it's not the word MYWORD) 
[^"]  # any character except a quote 
|   # or 
"\s*  # an ending quote, optional whitespace, 
\+\s*  # a plus sign, optional whitespace (including newlines), 
"   # and another opening quote. 
)*   # Repeat as needed. 
"\s*;  # Match a closing quote, optional whitespace, and a semicolon. 
相關問題