James
James

Reputation: 1548

Does JavaScript regex matching require repeated code?

Consider the following regex code snippet in Perl:

if ($message =~ /^(.+) enters the race!$/)) {
    $racer = $1;
    print "Found $racer";
} else {
    print "Racer parsing error!";
}

I'm trying to port this to JavaScript, and here's what I have come up with:

if (message.match(/^.+ enters the race!$/)) {
    var racer = message.match(/^(.+) enters the race!$/)[1];
    console.log("Found " + racer);
} else {
    console.log("Racer parsing error!");
}

Notice how the regex has to be repeated twice. This look sloppy. Not to mention that it wastes processing power since it has to do the same regex twice in a row. Is there any way to make this code snippet look cleaner?

Upvotes: 3

Views: 57

Answers (5)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626709

There are some differences between the code you have in Perl and JS:

  • JS does not have string interpolation, so your code has to be a bit verbose
  • There are no $1-like global variables, though you can declare it and use in code.

You can first match and check if the regex matched anything.

var message = "John enters the race!";
var m = message.match(/^(.+) enters the race!$/); // Match the string with a pattern
if (m) {                                          // Check if there is a match
    var racer = m[1];                             // Assign the captured substring to `racer`
    console.log("Found " + racer);              
} else {
    console.log("Racer parsing error!");
}

Note that m here is a Match object containing:

  • m[0] - the whole matched text
  • m[1] - the contents of Group 1 (capture group 1)
  • m.index - the 0-based index of the match in the string
  • m.input - the original string

Upvotes: 1

leo.fcx
leo.fcx

Reputation: 6467

I think you should create a RegExp instance and use test() and exec() methods as follows:

var myRegExp = new RegExp('^(.+) enters the race!$');

var message = 'Someone enters the race!';

if (myRegExp.test(message)) {
  var racer = myRegExp.exec(message)[1];
  console.log('Found ' + racer);
} 
else {
  console.log('Racer parsing error!');
}

Note the usage of ( and ) in the regular expression.

Upvotes: 0

jmcgriz
jmcgriz

Reputation: 3358

You can run the match command once. If it fails, getmatches will be null. If it's successful, getmatches[1] will contain your racer's name

var rgx = /^(.+) enters the race!$/,
  message = window.prompt('Enter Message'),
  getmatches = message.match(rgx);
if (getmatches) {
  var racer = getmatches[1];
  console.log("Found " + racer);
} else {
  console.log("Racer parsing error!");
}

Upvotes: 0

Keith Hall
Keith Hall

Reputation: 16055

You can store the match result in a variable:

var result = message.match(/^.+ enters the race!$/);
if (result) {
    var racer = result[1];
    console.log("Found " + racer);
} else {
    console.log("Racer parsing error!");
}

Upvotes: 1

ak_
ak_

Reputation: 2815

You can check the regex match right in the if statement. Something like this would work:

JavaScript

function check(message) {
    if (racer = message.match(/^(.+) enters the race!$/)) {
    console.log("Found " + racer[1]);
    } else {
    console.log("Racer parsing error!");
    }
}


check("blah enters the race!")
check("blah blah blah")

Output

Found blah
Racer parsing error!

Upvotes: 2

Related Questions