我知道如果你传递一个正则表达式,String的匹配方法就行了。但问题是如何撰写这样一个正则表达式。
涉及字符串的描述:
1. Skeleton :
字符串由以下结构组成:
' UNION(XXX,XXX,XXX,XXX,...)'
2. xxx :
' xxx '部分就像是' DESCENDANTS(" U0EXMDAW",会员(" U0EXMDAW"),SELF)'或者' DESCENDANTS(" U0EXMDAW",过滤器(DESCENDANTS(" U0EXMDAW",会员(" U0EXMDAW"),全部),"名称" =&# 34; adf"),ALL)'。
DESCENDANTS字符串可能包含几个像自己一样的DESCENDANTS字符串。 DESCENDANTS字符串的结构类似于' DESCENDANTS(" U0EXMDAW",成员(" U0EXMDAW"),SELF)'。
现在的问题是如何剥离 xxx '联合字符串中的部分?
输入:
' UNION(DESCENDANTS(" U0EXMDAW&#34 ;,成员(&#34) ; U0EXMDAW"),SELF),DESCENDANTS(" U0EXMDAW",FILTER(DESCENDANTS)" U0EXMDAW",会员(" U0EXMDAW"),ALL),& #34;姓名" =" adf"),ALL))'
输出:
[' DESCENDANTS(& #34; U0EXMDAW",成员(" U0EXMDAW"),自我)',' DESCENDANTS(" U0EXMDAW",FILTER(DESCENDANTS)" U0EXMDAW",会员(" U0EXMDAW"),ALL),"名称" =" adf"),ALL)']
答案 0 :(得分:1)
也许一些正则表达式更适合,但我认为小解析器足够合适。
string = 'UNION(DESCENDANTS("U0EXMDAW", MEMBERS("U0EXMDAW"), SELF),DESCENDANTS("U0EXMDAW", FILTER(DESCENDANTS("U0EXMDAW", MEMBERS("U0EXMDAW"), ALL), "name" = "adf"), ALL))';
s = string.substring(6, string.length -1); //we strip out the 'union' and its parentheses
//Let's parse the children
children = [];
depth = 0;//number of parentheses we pass
while( s.length) {
var i =0;
for(i; i < s.length; i++) {
if(s[i] == "(") {
depth++;
}
if(s[i] == ")") {
depth--;
}
if(s[i] == "," && depth == 0) {
break;
}
}
children.push(s.substring(0, i));
s = s.substring(i+1);
}
console.log(children); // ['DESCENDANTS("U0EXMDAW", MEMBERS("U0EXMDAW"), SELF)', 'DESCENDANTS("U0EXMDAW", FILTER(DESCENDANTS("U0EXMDAW", MEMBERS("U0EXMDAW"), ALL), "name" = "adf"), ALL)']
答案 1 :(得分:0)
function parseSelectedFormulas(sMemberFormula) {
var selectedFormulas = [],
formulaString,
leftParenthesises = [];
if (-1 === sMemberFormula.indexOf("UNION")) {
selectedFormulas.push(sMemberFormula);
} else {
formulaString = sMemberFormula.substring(6, sMemberFormula.length-1);
for(var i = 0; i < formulaString.length; i++) {
var char = formulaString.charAt(i);
switch(char) {
case "(":
leftParenthesises.push(i);
break;
case ")":
if (leftParenthesises.length > 1)
leftParenthesises.pop();
else {
selectedFormulas.push(formulaString.substring(0, i+1));
leftParenthesises = [];
if (i !== formulaString.length)
formulaString = formulaString.substring(i+2);
else
formulaString = "";
i = -1;
}
break;
default: break;
}
}
}
return selectedFormulas;
}