gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:43:54 27 4
gpt4 key购买 nike

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

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

最佳答案

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

关于带有变量的 Javascript 正则表达式提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49245477/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com