2011-11-29 61 views
0

我想應用正則表達式來查找和替換輸入字符串中不需要的括號和運算符。使用正則表達式匹配括號排序和條件

以下是我的可能輸入:從a到d的4種類型。 [無效輸入]

a). 1 and (2 or 3)() 
b). (and 2) 
c). (or 4) 
d).() 

所有這4個都是無效的情況下,有效的人應爲[有效輸入]

a). 1 and 2 
b). (1 and 2) 
c). 1 and (2 or 4) 

基於這一要求,我寫的正則表達式,但我已經寫分爲兩部分,需要幫助將它們連接到單個正則表達式。

a). ([(]+[\s]*[)]+) -> to find the empty parenthesis 
b). (([(]+[\s]*[and|or]+[\s]*)) -> to find cases like b or c in invalid inputs. 

請提出一種方法來結合上述。進一步我想要刪除輸入中的無效部分,我可以在javascript中像string.replace(regex)那樣去除輸入中的無效部分。

請分析此過程並給予意見。

+0

目前尚不清楚,你只想驗證輸入,或者你想試探性地從錯誤中清除它。從我的角度來看,第二種方法是行不通的。 – dhblah

+3

我認爲你誤解了方括號'['和']'。例如[和| or]表示六個字符'a','n','d','|','o','r'中的任何一個。 –

+5

這類問題不適合正則表達式。你有什麼基本上是遞歸語法,正則表達式無法處理它們。因爲它的遞歸是有限的,只允許一個嵌入級別,所以它可以用在正則表達式中,但是解決方案可能會很複雜和不清楚。 –

回答

1
/\((\s*|\s*(?:and|or)\s*\d+\s*|\s*\d+\s*(?:and|or)\s*|\s*(?:and|or)\s*)\)/ 

是用於檢查的托架對內容的正則表達式:要麼空的,在左邊,缺失操作數在右邊丟失操作數或根本沒有操作數。

但要小心!這既不檢查未加括號的表達式的有效性,也不像Colin Fine已經提到的那樣具有折衷性。如果你喜歡檢查,我建議從內部取代:

var s = string; 
var oneoperator = /^\s*\d+\s*(and|or)\s*\d+\s*$/; 
while (true) { 
    s = s.replace(/\(([^)])\)/, function(all, inner) { 
     if (inner.match(oneoperator) 
      return "0"; // or any other valid operand 
     else 
      throw new SyntaxError("Math Syntax mismatch"); 
    }); 
    if (s.match(oneoperator)) 
     break; // return true 
} 
// to be improved