Reputation: 9183
I have written the following regex to catch anything within two parenthesis of a text:
var rule = /[a-zA-Z0-9]*(\(+[a-zA-Z\s0-9]*\))*[a-zA-Z0-9\s]/;
It works in this website: http://regex101.com/ (javascript section)
Look the right side of the window and you see the bottom section shows the matched string which is what I want.
But in firebug when I execute the following code it crashes. Why? how then should I catch the group in parenthesis?
var rule = /^[a-zA-Z0-9\s]*(\(+[a-zA-Z\s0-9]*\))*[a-zA-Z0-9\s\,]*/;
var str = "He left us (with anger), but came back all cool and modest.";
var res = "";
while((res = rule.exec(str)) !== null)
{
console.log("Good");
}
console.log(res);
Or maybe I'm totally wrong and am missing something?
Upvotes: 0
Views: 72
Reputation: 10982
"But in firebug when I execute the following code it crashes. Why?"
To use .exec()
in a loop like that, the regex must be global. Otherwise it's just going to keep getting the first match, resulting in an infinite loop.
// make it global ------------------------------------------------v
var rule = /^[a-zA-Z0-9\s]*(\(+[a-zA-Z\s0-9]*\))*[a-zA-Z0-9\s\,]*/g;
When global, the regex object becomes stateful, and each subsequent .exec()
will begin from the character after the last match.
When there are finally no matches left, it'll return null
, breaking the loop.
As others pointed out in the comments, the leading ^
will guarantee only one match (without the m
modifier anyway), so you'll probably want to remove that. It's not the cause of the crash though.
Upvotes: 3