Regular expression in JavaScript not the same as in PHP

a6ghost

New Member
I have a regular expression to match usernames (which functions in PHP using \[code\]preg_match\[/code\]): \[code\]/[a-z]+(?(?=\-)[a-z]+|)\.[1-9][0-9]*/\[/code\]This pattern matches usernames of the form \[code\]abc.124\[/code\], \[code\]abc-abc.123\[/code\], etc.However, when I take this to JavaScript: \[code\]var re = new RegExp("/[a-z]+(?(?=\-)[a-z]+|)\.[1-9][0-9]*/"); \[/code\]I receive a syntax error: \[code\]SyntaxError: Invalid regular expression: /[a-z]+(?(?=-)[a-z]+|).[1-9][0-9]*/: Invalid group\[/code\]The \[code\](?(?=\-)[a-z]+|)\[/code\] is to say if after \[code\][a-z]+\[/code\] we see a \[code\]-\[/code\] then assert that \[code\][a-z]+\[/code\] 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: \[code\] 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); \[/code\]This alert comes up as \[code\]null\[/code\]? But if I do the following it works: \[code\]var patt=/[a-z]+(?:-[a-z]+)?\.[1-9][0-9]*/;var result=patt.exec(str);alert(result); \[/code\]Why does "new RegExp()" not work?
 
Back
Top