3

我有一个字符串,可以 C1 AND C2 OR C3 (~!@#$%) AND C4 OR C5 说我的输入是C3 然后我想使用正则表达式删除C3和下一个运算符之间的垃圾/数据AND|OR

所以对于上面的字符串,我想输出为C1 AND C2 OR C3 AND C4 OR C5

4

2 回答 2

0
function purgeJunk(variable, expression) {
    return expression.replace(purgeJunk.regexp, function(match, digits, operator) {
        if (digits != variable) return match;
        return "C" + digits + " " + operator;
    });
};

function purgeAllJunk(expression) {
    return expression.replace(purgeJunk.regexp, function(match, digits, operator) {
        return "C" + digits + " " + operator;
    });
};

purgeJunk.regexp = /C(\d+) .*?(AND|OR)/g;

// delete junk after C2
purgeJunk(2, "C1 AND C2 OR C3 (~!@#$%) AND C4 OR C5") 
    == "C1 AND C2 OR C3 (~!@#$%) AND C4 OR C5"

// delete junk after C3
purgeJunk(3, "C1 AND C2 OR C3 (~!@#$%) AND C4 OR C5") 
    == "C1 AND C2 OR C3 AND C4 OR C5"

// delete all junk
purgeAllJunk("C1 # AND C2 OR C3 ~!@#$% ()()()() ### AND C4 more garbage OR C5")
    == "C1 AND C2 OR C3 AND C4 OR C5"
于 2013-04-09T17:20:02.780 回答
0

尝试这个:

var str = 'C1 AND C2 OR C3 (~!@#$%) AND C4 OR C5'
var input = 'C3'
console.log(str.replace(new RegExp("(" + input + " ).*?(AND|OR)"), "$1$2"))
于 2013-04-09T15:19:14.217 回答