Skip to content Skip to sidebar Skip to footer

Intelligent Regex To Understand Input

Following Split string that used to be a list, I am doing this: console.log(lines[line]); var regex = /(-?\d{1,})/g; var cluster = lines[line].match(regex); console.log(cluster);

Solution 1:

For a simple way, you can use .replace(/(\d+)\s*,\s*/g, '$1') to merge/concatenate numbers in pair and then use simple regex match that you are already using.

Example:

var v1 = "((3158), (737))"; // singular stringvar v2 = "((3158, 1024), (737))"; // paired number stringvar arr1 = v1.replace(/(\d+)\s*,\s*/g, '$1').match(/-?\d+/g)
//=> ["3158", "737"]var arr2 = v2.replace(/(\d+)\s*,\s*/g, '$1').match(/-?\d+/g)
//=> ["31581024", "737"]

We use this regex in .replace:

/(\d+)\s*,\s*/
  • It matches and groups 1 or more digits followed by optional spaces and comma.
  • In replacement we use $1 that is the back reference to the number we matched, thus removing spaces and comma after the number.

Solution 2:

You may use an alternation operator to match either a pair of numbers (capturing them into separate capturing groups) or a single one:

/\((-?\d+), (-?\d+)\)|\((-?\d+)\)/g

See the regex demo

Details:

  • \((-?\d+), (-?\d+)\) - a (, a number (captured into Group 1), a ,, space, another number of the pair (captured into Group 2) and a )
  • | - or
  • \((-?\d+)\) - a (, then a number (captured into Group 3), and a ).

var re = /\((-?\d+), (-?\d+)\)|\((-?\d+)\)/g; 
var str = '((3158), (737)) ((3158, 1024), (737))';
var res = [];
while ((m = re.exec(str)) !== null) {
  if (m[3]) {
    res.push(m[3]);
  } else {
    res.push(m[1]+m[2]);
  }
}
console.log(res);

Post a Comment for "Intelligent Regex To Understand Input"