gpt4 book ai didi

javascript - 如何从字符串中获取映射值?

转载 作者:行者123 更新时间:2023-12-05 01:48:58 24 4
gpt4 key购买 nike

我有一个字符串,比如

const string =
"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";

由此,我需要映射相应的键和值,如 DEVICE_SIZE: ["036", "048", "060", "070"]

当前结果:

  const string =
"DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";

const res = string.split('IN ');

const regExp = /\(([^)]+)\)/;

const Y = 'AND';

const data = res.map((item) => {
if (regExp.exec(item)) {
return {
[item.slice(item.indexOf(Y) + Y.length)]: regExp.exec(item)[1],
};
}
});

console.log('data ', data);

预期结果:

[
{ "DEVICE_SIZE": ["036", "048", "060", "070"] },
{ "DEVICE_VOLTAGE": ["1", "3"] },
{ "NOT DEVICE_DISCHARGE_AIR": ["s"] },
{ "NOT DEVICE_REFRIGERANT_CIRCUIT": ["H", "C"] },
];

根据我对当前结果的尝试,我无法得到准确的结果。能否请您帮助我实现上述给定的预期结果?

注意:我正在尝试上述操作以实现我上一个问题中提到的最终结果 How to get valid object from the string matching respective array?

最佳答案

您可以使用带有 2 个捕获组的单个正则表达式来匹配键和值。

((?:\bNOT\s+)?\w+)\s+IN\s+\('([^()]*)'\)

参见 regex demo .

模式匹配:

  • ( 捕获组 1
    • (?:\bNOT\s+)? 可选择匹配单词 NOT 后跟 1+ 个空白字符
    • \w+ 匹配1个或多个单词字符
  • ) 关闭群组
  • \s+IN\s+ 匹配空白字符之间的单词 IN
  • \(' 匹配('
  • ([^()]*) 捕获第 2 组,匹配除 () 之外的任何字符的 1+ 次出现
  • '\)匹配')

要为对象创建动态键,您可以使用 Object Initializer并且您可以拆分 ',' 以创建值的结果数组。

const regex = /((?:\bNOT\s+)?\w+)\s+IN\s+\('([^()]*)'\)/g;
const string = "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";
const data = Array.from(
string.matchAll(regex), m =>
({
[m[1]]: m[2].split("','")
})
);
console.log(data);

关于javascript - 如何从字符串中获取映射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74581492/

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