3

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?

1
  • Might as well just do if (racer = message.match(/^(.+) enters the race!$/)[1] ) { ..} else { ..} Commented Mar 1, 2016 at 20:09

5 Answers 5

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

@WiktorStribiżew if the capture group is empty, there is no regex match and the else statement is triggered.
1

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

Comments

1

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!");
}

Comments

0

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!");
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.