I have a regular expression to match usernames (which functions in PHP using preg_match):
/[a-z]+(?(?=\-)[a-z]+|)\.[1-9][0-9]*/
This pattern matches usernames of the form abc.124, abc-abc.123, etc.
However, when I take this to JavaScript:
var re = new RegExp("/[a-z]+(?(?=\-)[a-z]+|)\.[1-9][0-9]*/");
I receive a syntax error:
SyntaxError: Invalid regular expression: /[a-z]+(?(?=-)[a-z]+|).[1-9][0-9]*/: Invalid group
The (?(?=\-)[a-z]+|) is to say if after [a-z]+ we see a - then assert that [a-z]+ is after it otherwise, match nothing. This all works great in PHP, but what am I missing about JavaScript that is different?
EDIT: I appreciate the comments, and now I have one last question regarding this:
var str="accouts pending removal shen.1206";
var patt= new RegExp("/[a-z]+(?:-[a-z]+)?\.[1-9][0-9]*/");
var result=patt.exec(str);
alert(result);
This alert comes up as null? But if I do the following it works:
var patt=/[a-z]+(?:-[a-z]+)?\.[1-9][0-9]*/;
var result=patt.exec(str);
alert(result);
Why does "new RegExp()" not work?
(?partnewin JS, I avoidnew RegExp. Note that both of the answers posted so far are using the literal form rather thannew: developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions