简体   繁体   English

带有变量的Javascript正则表达式提取

[英]Javascript regex extract with variable

I'd like to extract values from below key:value pairs being sent in as a single string: 我想从下面的key:value对中提取值作为单个字符串发送:

"var1:value1,var2:value2,var3:value3"

I have to use JavaScript and unfortunately I am unable to use an array and loop through the var1,var2,var3 keys due to the regex unable to handle variables... I am wondering if there is a way to do this in JS? 我必须使用JavaScript,但由于正则表达式无法处理变量,因此我无法使用数组并遍历var1,var2,var3键...我想知道是否有办法在JS中做到这一点?

See below: 见下文:

function onBefore(current, previous) 
{
if (current.key != '' || current.key != null) 
{
    if (current.key.match(/var1/)) {
    var assign = current.key.match(/(?:var1:)([^,]+)/)[1];
    } else if (current.key.match(/var2/)) {
    var assign = current.key.match(/(?:var2:)([^,]+)/)[1];
    } else if (current.key.match(/var3/)) {
    var assign = current.key.match(/(?:var3:)([^,]+)/)[1];
    } else if (current.key.match(/var4/)) {
    var assign = current.key.match(/(?:var4:)([^,]+)/)[1];
    }
    } else {
        assign = "None";
    }
    if (assign != "None") {
    current.node = assign;
    }
}
}

@revo thanks for that answer, for others to benefit... here's the final code: @revo感谢您的回答,其他人也可以从中受益...这是最终代码:

  var str = "keyIcareabout:test3end,something:value,nothing:burger"; var node = "None"; function valueOf(key) { return (m = (new RegExp("\\\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null; } if (str != '' || str !== null) { var resources = ["keyIcareabout","somethingelseIcareabout"]; for (i = 0; i < resources.length; i++) { if (str.match(resources[i])) { node = valueOf(resources[i]); } } } if (node != "None") { console.log("Matched " + node + " with node field "); } 

Use String.split : 使用String.split

 const data = 'var1:value1,var2:value2,var3:value3'; const pairStrings = data.split(/,/g); const pairs = pairStrings.map(pairString => pairString.split(/:/)); const object = pairs.reduce((object, [key, value]) => { object[key] = value; return object; }, {}); console.log(object); 

You underestimated RegEx. 您低估了正则表达式。 Your whole function could be shorten to this: 您的整个功能可以简化为:

function valueOf(key) {
   return (m = (new RegExp("\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null;
}

You don't have to check for each key individually in an if condition. 您无需在if条件下单独检查每个键。 Pass key to above valueOf() function to retrieve the value. key传递给上述valueOf()函数以检索该值。

 var str = "aws_acnt_name:test,aws_acnt_num:1234," + "host:identity01.auth-test,region:us-west-2,snow_sg:aws_cloud"; function valueOf(key) { return (m = (new RegExp("\\\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null; } console.log(valueOf('host')); console.log(valueOf('aws_acnt_name')); 

You can use a regex RegExp.exec() to loop through matches of key/value pairs, and extract the key and value to an object (or an array): 您可以使用正则表达式RegExp.exec()遍历键/值对的匹配,并将键和值提取到对象(或数组):

 var str = 'var1:value1,var2:value2,var3:value3'; var pattern = /([^:,]+):([^,]+)/g; var obj = {}; var temp; while(temp = pattern.exec(str)) { obj[temp[1]] = temp[2]; } console.log(obj); 

Edit- deleting my answer as suggested by vasan, we need to have quotes around the key and values. 编辑-根据vasan的建议删除我的答案,我们需要在键和值两边加上引号。 Rather than adding quotes and then parsing it will be better to just split it using split function. 与其添加引号然后进行解析,不如使用split函数将其拆分会更好。 So SimpleJ's answer should work. 因此,SimpleJ的答案应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM