Regex is an invalid target for a quantifier that converts a C # regular expression to JavaScript regex

I am trying to convert a C # email regular expression that I took from a MSDN sample

@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@)) (?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$" 

which is as follows:

 ^(?(")(".+?"@)|(([0-9a-zA-Z]((\.(?!\.))|[^!#\$%&\s'\*/=\?\^`\{\}\|~])*)(?<=[-+0-9a-zA-Z_])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z]{2,6}))$ 

but I get an error:

? . Invalid target for qualifier.

? <= : Lookbehind is not supported in JavaScript

I need help converting above regex

+5
source share
1 answer

In .NET, this regular expression should be used with the IgnorePatternWhitespace and IgnoreCase , since there is space that prevents a match. Here is a demon.

The problems you encounter when porting a regular expression to JS are because the JS regular expression does not support lookbehinds and conditional expressions.

There is a conditional workaround for JS: .NET (?(")"[^"]*"|\w+) can be translated as (?:(?=")"[^"]*"|(?!")\w+) .

Samples are hard to convert, but here the first lookbehind does not seem appropriate. You are looking to find the closest set of unshielded double quotes. You can do this with "[^"\\]*(?:\\.[^"\\]*)*" .

The second lookbehind simply checks if @ preceded by a letter or number. The easiest way to handle this is to add the character class [a-z0-9] left of the @ character and apply a quantifier ? to the first group of this alternative, making a number or letter before @ and the user part with 1 character will still match.

So you can use

 /^(?:(?=")("[^"\\]*(?:\\.[^"\\]*)*"@)|(?!")(([0-9a-z]((\.(?!\.))|[-!#$%&'*+\/=?^`{}|~\w])*)?[a-z0-9]@))(?:(?=\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(?!\[)(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][-a-z0-9]{0,22}[a-z0-9]))$/i 

See demo (note, I also deleted unnecessary escape characters).

+2
source

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


All Articles