MortenB
MortenB

Reputation: 3547

A simpler way to capture multiple variables in javascript regexps

Comming from the perl/python world I was wondering if there is a simpler way to filter out multiple captured variables from regexp in javascript:

#!/usr/bin/env node  
var data=[
  "DATE: Feb 26,2015",
  "hello this should not match"
];

for(var i=0; i<data.length; i++) {
  var re = new RegExp('^DATE:\\s(.*),(.*)$');
  if(data[i].match(re)) {
    //match correctly, but how to get hold of the $1 and $2 ?
  }
  if(re.exec(data[i])) {
    //match correctly, how to get hold of the $1 and $2 ? 
  }

  var ret = '';
  if(data[i].match(re) && (ret = data[i].replace(re,'$1|$2'))) {
    console.log("line matched:" + data[i]);
    console.log("return string:" + ret);
    ret = ret.split(/\|/g);
    if (typeof ret !== 'undefined') {
      console.log("date:" + ret[0], "\nyear:" + ret[1]);
    }
    else {
      console.log("match but unable to parse capturing parentheses");
    }
  }
}

The last condition works, but you need a temp var and split it, and you need to have a test in front because the replace works on everything.

Output is:

$ ./reg1.js 
line matched:DATE: Feb 26,2015
return string:Feb 26|2015
date:Feb 26 
year:2015

If I look up: mosdev regexp it says on (x):

The matched substring can be recalled from the resulting array's elements 1, ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

How do I get hold of the RegExp objects' $1 and $2?

Thanks

Upvotes: 0

Views: 1674

Answers (3)

Downgoat
Downgoat

Reputation: 14371

Using JavaScript .test() and .match() this can be very simple

An example:

var input = "DATE: Feb 26, 2015",
    regex = /^DATE:\s*(.*),\s*(.*)$/;

if (regex.match(input)) {
    console.log('Matches Format!');

    //.match() needs splicing because .match() returns the actually selected stuff. It becomes weirder with //g  
    var results = input.match(regex).splice(0,1);

    console.log(results);
    //Logs: ["Feb 26", "2015"]
}

Regex101 can be useful

Upvotes: 0

MortenB
MortenB

Reputation: 3547

Thanks for the answer found that they return an array:, so the simpler blocks can look like this:

  if((ret = data[i].match(re))!=null) {
    //match correctly, but how to get hold of the $1 and $2 ?
    console.log("line matched:" + data[i]);
    console.log("return string:" + ret[0] + "|" + ret[1]);
    ret = null;
  }
  if((ret = re.exec(data[i]))!=null) {
    //match correctly, how to get hold of the $1 and $2 ?
    console.log("line matched:" + data[i]);
    console.log("return string:" + ret[0] + "|" + ret[1]);
    ret = null;
  }

Upvotes: 0

mscdex
mscdex

Reputation: 106726

The MDN is a good resource for learning Javascript. In this particular case, .match(), .exec(), etc. all return objects containing match information. That is where you'll find captured groups.

Upvotes: 3

Related Questions