Home > Back-end >  The regular expression works with Chrome and Firefox browsers but not on safari
The regular expression works with Chrome and Firefox browsers but not on safari

Time:11-18

This is the RegEx.

/^[a-zA-Z] (?!.*?\.\.)(?!.*?\-\-)[a-zA-Z0-9.-]*(?<!\.)(?<!\-)$/

It works with Chrome and Firefox browsers but fails on Safari browser with the error:

Invalid regular expression:invalid group specifier name

CodePudding user response:

First thing, you should understand what your regex pattern does (or matches).

  • ^ - start of string
  • [a-zA-Z] - one or more letters
  • (?!.*?\.\.) - no two consecutive dots allowed after any zero or more chars other than line break chars as few as possible
  • (?!.*?\-\-) - no two consecutive dots allowed after any zero or more chars other than line break chars as few as possible
  • [a-zA-Z0-9.-]* - zero or more letters, digits, . or -
  • (?<!\.)(?<!\-)$ - the end of string with no . nor - immediately on the left.

So, what you want to match is a string that starts with letters, then contains alphanumeric chars "interleaved" with dots or hyphens, but -- and .. are forbidden.

The identical pattern without a lookbehind will look like

/^[a-zA-Z](?!.*?\.\.)(?!.*?--)(?!.*[.-]$)[a-zA-Z0-9.-]*$/

Here, (?!.*[.-]$) requires to fail the match if there is a . or -at the end of the string. You should also emove the first `, it will allow backtracking when it is not necessary.

NOTE that the pattern above allows .- and -. in the string. If you do not want to allow that, simply use a no-lookaround pattern,

/^[a-z] (?:[-.][a-z0-9] )*$/i

The ^[a-z] (?:[-.][a-z0-9] )*$ pattern matches

  • ^ - start of string
  • [a-z] - one or more letters (case insensitive matching is enabled with /i flag)
  • (?:[-.][a-z0-9] )* - zero or more occurrences of - or . and then one or more letters/digits
  • $ - end of string.
  • Related