[英]How to ignore white space in string using regex?
I am having a query string and I parse it and form array of objects like,我有一个查询字符串,我解析它并形成对象数组,例如,
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);
Here ('036','048', '060','070')
has a additional white space before 060
, so the array formed looks like,这里
('036','048', '060','070')
在060
之前有一个额外的空白,所以形成的数组看起来像,
"DEVICE_SIZE": [
"036",
"048', '060",
"070"
]
But expected result is但预期的结果是
"DEVICE_SIZE": [
"036",
"048",
"060",
"070"
]
Kindly help me to ignore all the white spaces before any string.请帮助我忽略任何字符串之前的所有空格。
You need to change your split pattern to get right output:你需要改变你的分割模式才能得到正确的 output:
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);
Regex pattern /',\s*'/
will match closing '
and comma followed by 0 or more whitespaces and then opening '
, this removing whitespaces from the resulting split
array.正则表达式模式
/',\s*'/
将匹配结束'
和逗号后跟 0 个或多个空格,然后打开'
,这会从生成的split
数组中删除空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.