如何在JS中通过正则给NOT括号内的所有键添加NOT前缀?
解决NOT条件带括号的正则转换问题
我开发应用时需要将特定格式的字符串转换为键值对数组,现有逻辑可处理NOT DEVICE_XXX IN (...)格式,生成"NOT DEVICE_XXX"作为键,但遇到NOT (DEVICE_A IN (...) AND DEVICE_B IN (...))这种带括号的格式时,无法给括号内的每个DEVICE_*键添加NOT前缀。
现有代码如下:
const stringOne = "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 stringTwo = "DEVICE_SERIES IN ('LV') AND DEVICE_ELECTRICAL IN ('K') AND NOT (DEVICE_SERIES IN ('LV') AND DEVICE_VOLTAGE IN ('A','8') AND DEVICE_SIZE IN ('007','009','012','018'))"; const regex = /((?:\bNOT\s+)?\w+)\s+IN\s+\('([^()]*)'\)/g; const getTransformedData = (string) => { return Array.from( string.matchAll(regex), m => ({ [m[1]]: m[2].split(/',\s*'/) }) ) } console.log(getTransformedData(stringOne)); // 运行正常 console.log(getTransformedData(stringTwo)); // 需给每个键添加NOT前缀
修改后的实现方案
核心思路是先预处理带NOT的括号块,给括号内的每个DEVICE_*添加NOT前缀,再用原正则提取键值对:
const stringOne = "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 stringTwo = "DEVICE_SERIES IN ('LV') AND DEVICE_ELECTRICAL IN ('K') AND NOT (DEVICE_SERIES IN ('LV') AND DEVICE_VOLTAGE IN ('A','8') AND DEVICE_SIZE IN ('007','009','012','018'))"; const regex = /((?:\bNOT\s+)?\w+)\s+IN\s+\('([^()]*)'\)/g; // 匹配NOT后带括号的内容块 const notGroupRegex = /NOT\s*\(([^)]+)\)/g; const getTransformedData = (string) => { // 预处理:给NOT括号内的每个DEVICE_*添加上NOT前缀 const processedStr = string.replace(notGroupRegex, (_, innerContent) => { return innerContent.replace(/\bDEVICE_\w+\b/g, 'NOT $&'); }); // 沿用原逻辑提取键值对 return Array.from( processedStr.matchAll(regex), m => ({ [m[1]]: m[2].split(/',\s*'/) }) ) } console.log(getTransformedData(stringOne)); console.log(getTransformedData(stringTwo));
效果说明
修改后处理stringTwo时,括号内的DEVICE_SERIES、DEVICE_VOLTAGE、DEVICE_SIZE都会被加上NOT前缀,生成预期的键值对:
{"NOT DEVICE_SERIES": ["LV"]}{"NOT DEVICE_VOLTAGE": ["A", "8"]}{"NOT DEVICE_SIZE": ["007","009","012","018"]}
内容的提问来源于stack exchange,提问作者Hello World
相关产品推荐
相关产品推荐

