regex 如何使用正则表达式忽略字符串中的空格?

mzsu5hc0  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(155)

我有一个查询字符串,我解析它并形成一个对象数组,

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

这里('036','048', '060','070')060之前有一个额外的空白,因此形成的数组看起来像,

"DEVICE_SIZE": [
      "036",
      "048', '060",
      "070"
    ]

预期结果

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

请帮助我忽略任何字符串前的所有空格。

yvfmudvl

yvfmudvl1#

您需要更改拆分模式以获得正确的输出:

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(/',\s*'/)
  })
);
console.log(data);

正则表达式模式/',\s*'/将匹配右'和逗号,后跟0个或多个空格,然后匹配左',这将从结果split数组中删除空格。

相关问题