regex 如何在JS中使用正则表达式在字符串前添加关键字?

8zzbczxx  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(106)

我正在制作一个应用程序,其中我有一个字符串,我将在regex的帮助下从该字符串形成一个数组。
例如:
字符串:DEVICE_SIZE IN ('036','048', '060','070')
输出量:

{
    "DEVICE_SIZE": [
      "036",
      "048",
      "060",
      "070"
    ]
}

像这样对于所有字符串,我们按照下面的代码来获取数组数据。
这里,如果在key之前有一个NOT关键字,那么我们就像"NOT DEVICE_DISCHARGE_AIR"一样添加NOT *key*

要求:

我有一个类似NOT (DEVICE_SERIES IN ('LV') AND DEVICE_VOLTAGE IN ('A','8') AND DEVICE_SIZE IN ('007','009','012','018'))的字符串。
NOT后面有一个括号,在NOT后面如果有一个括号,我需要添加键
"NOT DEVICE_SERIES":["LV"]
"NOT DEVICE_VOLTAGE":["A", "8"]
"NOT DEVICE_SIZE": ['007','009','012','018']

当前方案:

但是现在,它没有在key之前添加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)); // Working fine

console.log(getTransformedData(stringTwo)); // Need to include NOT infront of each key as it is union

我如何在每个键前面添加NOT关键字,如果它带有NOT模式,然后是括号,如stringTwo

预期结果:

"NOT DEVICE_SERIES":["LV"]
"NOT DEVICE_VOLTAGE":["A", "8"]
"NOT DEVICE_SIZE": ['007','009','012','018']

5lwkijsr

5lwkijsr1#

您可以使用此Javascript解决方案来解决您的问题:

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 ('ALV', 'FOO') 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 pat1 = String.raw`(\bNOT)\s+\(((?:[\w\s]+\([^)]+\))+)\)`;
const pat2 = String.raw`(\w+)\s+IN\s+\('([^()]*)'\)`;
const re1 = new RegExp(pat1 + '|' + pat2, "g");
const re2 = new RegExp(pat2, "g");
const re3 = /',\s*'/;

const getTransformedData = (string) => {
  var res = [];
  const matches = string.matchAll(re1);
  for (const match of matches) {
    if (match[1] == "NOT") {    
      res.push(...Array.from(
      match[2].matchAll(re2), m =>
      ({
        [match[1] + ' ' + m[1]]: m[2].split(re3)
      })));
    } else {
      res.push(
      ({
        [match[3]]: match[4].split(re3)
      }));
    }
  }
  return res;
}

console.log(getTransformedData(stringOne));
console.log(getTransformedData(stringTwo));
  • 正则表达式字符串pat2与您已有的相同
  • 正则表达式字符串pat1与包含NOT (...)子字符串的字符串匹配。
  • 我们将pat1pat2结合起来构建一个正则表达式re1,首先将其应用于输入字符串。该正则表达式匹配NOT (...)模式或word in (...)子模式。
  • 我们在撷取群组#1中撷取NOT,并在撷取群组#2中撷取(...)内的文字。
  • match[1] == "NOT"时,我们在match[2]上再次应用re2,以获得所需的匹配
  • 正则表达式re3是拆分正则表达式

相关问题