我正在尝试提取字符串的一部分并使用javascript中的regex替换它。例:
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开始之前停止。
发布于 2017-09-21 12:21:22
您的regex的意思是“查找任何'=‘符号,后面跟着一个或多个字符。”
您可以查看https://regex101.com/,它提供了调试regex的可视化方法。
试试string.replace(/(packet\.vlan == )(\d+)/, "$1VLAN-$2");
注意:"string“是变量的一个非常糟糕的名称。
发布于 2017-09-21 12:23:21
可以使用regex替换字符串,RegExp中的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"));
发布于 2017-09-21 12:18:56
解决方案是重写regex:
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字符串?
https://stackoverflow.com/questions/46343642
复制相似问题