Reputation: 1548
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
Reputation: 626709
There are some differences between the code you have in Perl and JS:
$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 textm[1]
- the contents of Group 1 (capture group 1)m.index
- the 0-based index of the match in the stringm.input
- the original stringUpvotes: 1
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
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
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
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