我试图提取字符串的一部分并在javascript中使用正则表达式替换它。 例如:
var string = "application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1"
我需要替换
packet.vlan == 10
带
packet.vlan == VLAN-10
我试过以下
var regexp = /(\=.+)/g;
string.replace(regexp, ("==" + "VLAN-10");
选择必须在下一个OR/AND
停止。如果例如上述选择必须在字符串ip
开始之前停止。
答案 0 :(得分:1)
你的正则表达式意味着“找到任何'='符号后跟一个或多个字符。”
您可以查看https://regex101.com/,它提供了调试正则表达式的可视方式。
尝试string.replace(/(packet\.vlan == )(\d+)/, "$1VLAN-$2");
注意:“string”是变量的一个非常糟糕的名称。
答案 1 :(得分:1)
您可以使用正则表达式替换字符串,g
中的RegExp
标识符用作global
匹配(查找所有匹配项,而不是在第一次匹配后停止)。
var string = "application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1"
var temp = new RegExp("packet.vlan == 10", "g");
console.log(string.replace(temp, "packet.vlan == VLAN-10"));
要将packet.vlan == 10
的第一次出现替换为VLAN-10
,您只需使用.replace()
。
var string = "application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1 AND packet.vlan = 11.1.1.1.11"
console.log(string.replace("packet.vlan == 10", "packet.vlan == VLAN-10"));
答案 2 :(得分:0)
解决方案是重写你的正则表达式:
var regexp = /(==\s)(.+\b)/g; //all chars from ==whitespace until next word boundery
var s = "packet.VLAN == 10".replace(regexp, "== VLAN-$2"); //$2 to refer to the capturing group
console.log(s);

然而,对于这些复杂的sql
字符串,我会使用其他JavaScript来确保更多控制。看看:
var SQLString = "application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1";
var edit = SQLString.split(/AND|OR/i); //split on and or
var andOrs = SQLString.match(/AND|OR/ig); //create an array with and an or.
edit.forEach(function(value, index, arr){
//loop the array
var prop = value.substr(0, value.trim().search(/\s/)+1).trim(); //trim the whitespaces.
switch(prop){
case "packet.vlan" :
arr[index] = "packet.vlan == VLAN-" +value.split("==")[1].trim();
break;
}
//add the original and or to it.
andOrs[index] ? arr[index] = arr[index].trim() + " " + andOrs[index].trim() : null;
});
SQLString = edit.join(" "); //join the array parts with a whitespace.
console.log(SQLString);

最后一点。我很好奇为什么需要JavaScript来重写SQL字符串?
答案 3 :(得分:0)
试试这个,
const regex = /packet.vlan == (\d+)/g;
const str = `application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1`;
const subst = `packet.vlan == VLAN-$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
请参阅正则表达式:https://regex101.com/r/93AfJr/1
OR
const str = `application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1`;
var newstr = str.replace(/packet.vlan == 10/i, 'packet.vlan == VLAN-10');
console.log(newstr);
答案 4 :(得分:0)
因为我必须找到packet.xxx的字符串并用值替换它。我不得不循环查找包含数据包的字符串。并使用正则表达式替换它。
注意:在packet.xxx中,xxx可以是任何动态值。