2010-08-04 17 views
0

我有一些存儲在數據庫表中的繼承遺留語言代碼片段,我需要將它轉換爲類似於SQL的語法,以便更有效地使用它。使用正則表達式更改語法

例如,片段中的一個是所述形式的

keyword = [a,b,c,x:y,d,e,f,p:q] 

以指示離散的逗號分隔值或一個範圍的冒號分隔的值

我怎樣才能變換此爲等效SQL友好的片斷這將是

keyword in (a,b,c) or keyword between x and y or keyword in (d,e,f) or keyword between p and q 

感謝

+0

如果你希望做一個單一的正則表達式替換:你最有可能不能使用,因爲大多數工具/語言,你只能更換一個模式用一個替換字符串。你不能用'replacementA'替換'patternA',而用'replacementB'替換'patternB'。那麼,你會用什麼工具來替代這些替代品? – 2011-02-19 14:54:53

回答

0

這不是正則表達式,但第一這一點,想到它提取的方括號內的文字讓你有

textVariable = a,b,c,x:y,d,e,f,p:q 

然後用柱拆分,所以你有一個數組,其中每個元素都是字符串的一部分。所以你得到的陣列將是

array[0] = a 
... 
array[3] = x:y 
... 

然後通過你的數組,並創建你想要的最終字符串。這樣的事情(雖然未經測試)

finalString = "" 
tempString = "" 
for (int i = 0, i < array.length; i++) { 
    if (array[i].contains(":")) { // then it needs to be between the two values 
     if (finalString.length > 0) { 
     finalString = finalString + " or "; // need to add an 'or' 
     } 
     if (tempString.length > 0) { // then need to add the keyword in (...) to finalString 
     finalString = finalString + tempString + ") or "; 
     } 
     temparray = array[i].split(":") 
     finalString = finalString + " keyword between " + temparray[0] + " and " + temparray[1] 
    } else { 
     if (tempString.length = 0) { 
     tempString= "keyword in ("; // need to start the next set 
     } else { 
     tempString = tempString + ", " 
     } 
     tempString = tempString + array[i]; 
    } 
} 
+0

我希望使用正則表達式會導致更簡潔的解決方案,而不是枯燥的舊字符串解析。 :-) 可以在子表達式中捕獲關鍵字和值的每個值/範圍,並且替換字符串可以使用IN或BETWEEN重放表達式,具體取決於捕獲的值是否具有冒號。 感謝:-) – 2010-08-04 15:57:04

+0

沒問題..這只是想我想到了第一。認爲這會比沒有好。 :) – Kyra 2010-08-04 16:07:10

+1

我有時會認爲正則表達式的人越少,他們認爲它就能爲他們做的越多! :) – 2011-02-19 14:57:03