首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用regex和javascript只提取字符串的一部分

使用regex和javascript只提取字符串的一部分
EN

Stack Overflow用户
提问于 2017-09-21 12:13:15
回答 5查看 126关注 0票数 1

我正在尝试提取字符串的一部分并使用javascript中的regex替换它。例:

代码语言:javascript
复制
var string = "application == xyz AND location == abc AND packet.vlan == 10 OR ip == 1.1.1.1" 

我需要替换

代码语言:javascript
复制
packet.vlan == 10 

使用

代码语言:javascript
复制
packet.vlan == VLAN-10

我试过以下几种方法

代码语言:javascript
复制
var regexp = /(\=.+)/g;
string.replace(regexp, ("==" + "VLAN-10");

选择必须在下一个OR/AND停止。在上述情况下,选择必须在字符串ip开始之前停止。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-09-21 12:21:22

您的regex的意思是“查找任何'=‘符号,后面跟着一个或多个字符。”

您可以查看https://regex101.com/,它提供了调试regex的可视化方法。

试试string.replace(/(packet\.vlan == )(\d+)/, "$1VLAN-$2");

注意:"string“是变量的一个非常糟糕的名称。

票数 1
EN

Stack Overflow用户

发布于 2017-09-21 12:23:21

可以使用regex替换字符串,RegExp中的RegExp标识符用作global匹配(查找所有匹配项,而不是在第一次匹配之后停止)。

代码语言:javascript
复制
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()即可。

代码语言:javascript
复制
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"));

票数 1
EN

Stack Overflow用户

发布于 2017-09-21 12:18:56

解决方案是重写regex:

代码语言:javascript
复制
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来确保更多的控制。看一看:

代码语言: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字符串?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46343642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档