简体   繁体   中英

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,

"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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM