2014-10-11 36 views
0

我試圖實施某種動態過濾。使用RegExp過濾條件和組中的字符串

比方說,我有一個對象的集合。每個對象具有相同的鍵但不同的值。

例:

{ 
    "state":"time out", 
    "displayState": "error" 
} 

我要篩選和分類,他們下面的字符串中提取的模式。

EX(任何意義,只是推測):

"displayState=error&(state!=aborted|(state=cancelled&state=timed out))" 

我認爲這個儀器串將通過正則表達式的最好方法。爲了能趕上小組,操作數和運算

Here's what I have for now

([^|&!()=<>]*)([=!<>]{1,2})([^|&!()=<>]*)(?:([|&])\(?([^|!&()=<>]*)([=!<>]{1,2})([^|&!()=<>]*)\)?)? 

這是基本的和線性的,我的正則表達式的知識是有限的,所以它沒有做什麼,我需要。

基本上我試圖通過()第一個,然後[.*][=><!][.*]

在同一進程中捕獲組,操作數和運算符。

- 編輯 -

感謝Aniket's answer我能得到遠一點。

如上所述intheseanswers,正則表達式不能做遞歸,至少不能用Javascript。

因此,由()分隔的組不能僅通過regexp隔離,並且需要一些邏輯。

我查看Aniket's regexp清潔漁獲

/([&|])?\(*(([a-zA-Z0-9 ]*)([!=<>]+)([a-zA-Z0-9 ]*))\)*/g

將返回

0 : { 
    expression : displayState=error 
    type : undefined 
    operand1 : displayState 
    operator : = 
    operand2 : error 
}, 
1 : { 

    expression : &(state!=aborted 
    type : & 
    operand1 : state 
    operator : != 
    operand2 : aborted 
}, 
2 : { 
    expression : |(state=cancelled 
    type : | 
    operand1 : state 
    operator : = 
    operand2 : cancelled 
}, 
3 : { 
    expression : |state=timed out)) 
    type : | 
    operand1 : state 
    operator : = 
    operand2 : timed out 
} 

我正在使用JavaScript隔離羣體,並擁有一套完整的jsfiddle工作流程。

我會在我的解決方案正常工作後發佈。

+0

'state = timed out' should not be quoted like'state ='timed out''? – anubhava 2014-10-11 04:46:09

+0

它不會改變任何東西。我是編譯字符串的人,所以這個空間不是一個保留字符,也不能在這個上下文中轉義。 – YoannM 2014-10-11 22:14:43

+0

很難從上面的表達中理解你需要輸出什麼。你自己的正則表達式不是通過忽略'('和')'來改變整個表達式的含義。 – anubhava 2014-10-12 06:55:15

回答

1

這是我已經能夠拿出:

([\&\|\(]+)?([a-zA-Z0-9 ]*)([!=<>]+)([a-zA-Z0-9 ]*) 

http://www.regexr.com/39mfq

這會給你的團體,操作數和運算符。這裏有個警告,它只能抓住第一個左括號,所以你可以自己添加關閉的元素來檢查構造好的組。

假設我有上面給出此字符串

"displayState=error&(state!=aborted|(state=cancelled&state=timed out))" 

從正則表達式,我將得到以下組:

displayState 
= 
error 

&(
state 
!= 
aborted 

|(
state 
= 
cancelled 

& 
state 
= 
timed out 

這是相當簡單的計算這個,你可以通過檢查開始並打開(,如果你找到一個,那麼你知道它前面的表達式將被包含在其中。

我知道這不是一個很好的解決方案,但它可能會有所幫助。