我試圖實施某種動態過濾。使用RegExp過濾條件和組中的字符串
比方說,我有一個對象的集合。每個對象具有相同的鍵但不同的值。
例:
{
"state":"time out",
"displayState": "error"
}
我要篩選和分類,他們下面的字符串中提取的模式。
EX(任何意義,只是推測):
"displayState=error&(state!=aborted|(state=cancelled&state=timed out))"
我認爲這個儀器串將通過正則表達式的最好方法。爲了能趕上小組,操作數和運算
([^|&!()=<>]*)([=!<>]{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工作流程。
我會在我的解決方案正常工作後發佈。
'state = timed out' should not be quoted like'state ='timed out''? – anubhava 2014-10-11 04:46:09
它不會改變任何東西。我是編譯字符串的人,所以這個空間不是一個保留字符,也不能在這個上下文中轉義。 – YoannM 2014-10-11 22:14:43
很難從上面的表達中理解你需要輸出什麼。你自己的正則表達式不是通過忽略'('和')'來改變整個表達式的含義。 – anubhava 2014-10-12 06:55:15