Javascript正则表达式提取变量

时间:2018-03-12 22:37:50

标签: javascript arrays regex

我想从下面的键中提取值:作为单个字符串发送的值对:

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

我必须使用JavaScript,不幸的是我无法使用数组并循环访问var1,var2,var3键,因为正则表达式无法处理变量...我想知道是否有办法在JS?

见下文:

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感谢您的回答,让其他人受益......这里是最终的代码:



	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 ");
	}
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

使用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);

答案 1 :(得分:1)

你低估了RegEx。你的整个功能可以缩短到这个:

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

您不必在if条件下单独检查每个密钥。将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'));

答案 2 :(得分:0)

您可以使用正则表达式RegExp.exec()循环键/键对的匹配,并将键和值提取到对象(或数组):

&#13;
&#13;
const numbers = [1, 2, 3, 4, 5] -> This comes from the redux store
const listItems = numbers.map((number) =>
  <li>{number}</li>
);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

编辑 - 按照vasan的建议删除我的答案,我们需要在键和值周围加上引号。而不是添加引号然后解析它将更好地使用split函数拆分它。所以SimpleJ的答案应该有效。