2014-10-11 73 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 

这是相当简单的计算这个,你可以通过检查开始并打开(,如果你找到一个,那么你知道它前面的表达式将被包含在其中。

我知道这不是一个很好的解决方案,但它可能会有所帮助。