2013-04-09 39 views
3

我有一个字符串可以说C1 AND C2 OR C3 ([email protected]#$%) AND C4 OR C5 ,说我的输入C3 然后我想删除的垃圾/使用正则表达式C3和未来运营商之间AND|OR数据。字符串操作使用正则表达式

因此,对于上面的字符串,我想作为C1 AND C2 OR C3 AND C4 OR C5

+1

是垃圾数据总是用括号括起来?此外,你到目前为止尝试过什么? – 2013-04-09 15:10:08

+0

'不''它可以是任何东西前'C1和C2或C3〜!@#$%()()()()###和C4或C5' – Kumar 2013-04-09 15:11:50

+0

也需要提供输入C1/C2/C3 ....)作为输入可以是C2 ..其中没有任何垃圾..那么我不应该删除垃圾后C3 – Kumar 2013-04-09 15:14:24

回答

0

输出试试这个:

var str = 'C1 AND C2 OR C3 ([email protected]#$%) AND C4 OR C5' 
var input = 'C3' 
console.log(str.replace(new RegExp("(" + input + ").*?(AND|OR)"), "$1$2")) 
+0

这是非常具体的输入字符串并且在所有情况下都不起作用。 – 2013-04-09 15:19:41

+0

雅我需要通用溶胶 – Kumar 2013-04-09 15:24:28

+0

你将不得不C3取代你的输入。 – mrks 2013-04-09 15:27:35

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 ([email protected]#$%) AND C4 OR C5") 
    == "C1 AND C2 OR C3 ([email protected]#$%) AND C4 OR C5" 

// delete junk after C3 
purgeJunk(3, "C1 AND C2 OR C3 ([email protected]#$%) AND C4 OR C5") 
    == "C1 AND C2 OR C3 AND C4 OR C5" 

// delete all junk 
purgeAllJunk("C1 # AND C2 OR C3 [email protected]#$%()()()() ### AND C4 more garbage OR C5") 
    == "C1 AND C2 OR C3 AND C4 OR C5" 
相关问题