我有一个字符串可以说C1 AND C2 OR C3 (~!@#$%) AND C4 OR C5
并说我的输入是C3
然后我想使用正则表达式删除C3
和下一个运算符AND|OR
之间的垃圾/数据。
所以对于上面的字符串我希望输出为C1 AND C2 OR C3 AND C4 OR C5
答案 0 :(得分: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"))
答案 1 :(得分: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"