求一个正则表达式,来筛选一个复杂的功能


需求是这样的:
这里就当作是一个选配规则 (((A与B)(C或D)(E与A))(非F))((A或B)(非C))
然后有几个复选框,分别对应括号内的A/B/C/D/E/F

要求:
与或非三种,与C#语法的作用一样(&&,||,!=)
分解括号内的数据,分割成数组。
求出A/B/C/D/E/F中按最优先排列。

.net JavaScript

Mr.深海龟 10 years, 8 months ago

用正则不如用程序来实现,正则很难确定优先级的关系

   
  var str = '(((A与B)(C或D)(E与A))(非F))((A或B)(非C))';
  
function find(str) {
var index = 0;
var carr_mathces = matches = [];
var match_stack = [];
var finder = '';

do {
if(str[index] == '(') {
if(str[index + 1] == '(') {
carr_mathces[carr_mathces.length] = [];
match_stack.push(carr_mathces);
carr_mathces = carr_mathces[carr_mathces.length - 1]
}
} else if(str[index] == ')') {
if(finder != '') {
carr_mathces[carr_mathces.length] = finder;
finder = '';
}
if(str[index - 1] == ')') {
carr_mathces = match_stack.pop();
}
} else {
finder += str[index];
}
} while(++index < str.length)

return matches;
}

function print_r(theObj) {
var retStr = '';
if (typeof theObj == 'object') {
retStr += '<div style="font-family:Tahoma; font-size:7pt;">';
for (var p in theObj) {
if (typeof theObj[p] == 'object') {
retStr += '<div><b>['+p+'] => ' + typeof(theObj) + '</b></div>';
retStr += '<div style="padding-left:25px;">' + print_r(theObj[p]) + '</div>';
} else {
retStr += '<div>['+p+'] => <b>' + theObj[p] + '</b></div>';
}
}
retStr += '</div>';
}
return retStr;
}

document.write(print_r(find(str)));

其中print_r函数来自 javascript 如何打印多维数组及json数据对象

输出结果

请输入图片描述

迎风流泪君 answered 10 years, 8 months ago

Your Answer