Errors translating regex from .NET to javascript
I have this piece of VBNet code that i would like to translate into javascript:
Dim phone_check_pattern = "^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$"
System.Diagnostics.Debug.WriteLine(System.Text.RegularExpressions.Regex.IsMatch("test input", phone_check_pattern))
my translated result:
var phone_check_pattern = "^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$";
alert(new RegExp(phone_check_pattern).test("test input"))
However when i run it it has error Uncaught SyntaxError: Invalid regular expression:: Nothing to re开发者_如何学Cpeat
(my VbNet code doesn't have any error though)
Does anyone know what's causing the problem?
The backslash character in JavaScript strings is an escape character, so the backslashes you have in your string are escaping the next character for the string, not for the regular expression. So right near the beginning, in your "^(\+?
, the backslash there just escapes the +
for the string (which it doesn't need), and what the regexp sees is just a raw +
with nothing to repeat. Hence the error.
Fortunately, JavaScript has a literal syntax for regular expressions (delimited with /
characters), which would probably be a better starting point for you:
var re = /^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.\/-]|\([ 0-9.\/-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.\/-]|\([ 0-9.\/-]+\)))?$/;
alert(re.test("test input"));
Then at least the backslashes are escaping in the regex, not the string. (Note that since /
is the delimiter for the regular expression literal, we have to escape it (with a backslash).)
I haven't exhaustively reviewed the actual regexp, but that should get you started.
More about regular expression literals in the spec, of course, and here on MDC.
I'm not sure but try to use \\
instead of \
in your javascript code. Seen some samples that did this.
The double-slash, as everyone said, is important. This works:
var phone_check_pattern = "^(\\+?|(\\(\\+?[0-9]{1,3}\\))|)"+
"([ 0-9.//-]|\\([ 0-9.//-]+\\))+"+
"((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\\([ 0-9.//-]+\\)))?$";
var re = new RegExp(phone_check_pattern);
say(re.test("test input"));
say(re.test("(415) 828-3321"));
say(re.test("+1 (212) 828-3321"));
say(re.test("da828-3321"));
精彩评论