Errors translating a regular expression from .NET to javascript

I have this 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 is:

 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 an Uncaught SyntaxError: Invalid regular expression:: Nothing to repeat error

(my VbNet code has no error)

Does anyone know what causes the problem?

+6
source share
3 answers

The backslash character in JavaScript strings is an escape character, so the backslashes that you have in your string elude the next character for the string, not the regular expression. So, right at the beginning, in your "^(\+? Backslash just escapes + for the line (which doesn't need it), and what the regular expression sees is just raw + where nothing happens again. From here error.

Fortunately, JavaScript has a literal syntax for regular expressions (with delimiters with / characters), which is likely to be the best 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 backslashes are escaped in the regular expression, not in the string. (Note that since / is a delimiter for a regular expression literal, we need to avoid it (with a backslash).)

I have not exhaustively examined the actual regex, but this should get you started.

More on regex literals in the specification , of course, and here on the MDC .

+7
source

I'm not sure, but I will try to use \\ instead of \ in your javascript code. Saw some patterns that did this.

+2
source

Double slash, as everyone said, is important. It 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")); 
+1
source

Source: https://habr.com/ru/post/888509/


All Articles