Home > Software design >  Lookbehind works in Chrome, but breaks in Safari: Invalid regular expression invalid group
Lookbehind works in Chrome, but breaks in Safari: Invalid regular expression invalid group

Time:10-17

Works in Chrome, but breaks in Safari: Invalid regular expression: invalid group specifier name

/^(?=.{1,50}$)(?![_.-])(?!.*[_.-]{2})[a-z0-9._-] (?<![_.-])$/

CodePudding user response:

Guess the lookbehind is not supported by Safari JS regex. Good news, it's not needed here.

^(?![_.-])(?!.*[_.-]{2})[a-z\d._-]{0,49}[a-z\d]$

See this demo at regex101

Just another (self explaining) way to write the pattern without the lookbehind at the end.

CodePudding user response:

You can also use a singe lookahead assertion for the length, and then start and end the match with a char a-z0-9 not allowing consecutive matches for [._-]

^(?=.{1,50}$)[a-z\d] (?:[._-][a-z\d] )*$

Explanation

  • ^ Start of string
  • (?=.{1,50}$) Positive lookahead, assert 50 chars till the end of string
  • [a-z\d] Match 1 chars a-z0-9
  • (?: Non capture group
    • [._-][a-z\d] Match one of . _ -` and 1 chars of a-z0-9
  • )* Close the non capture group and optionally repeat it
  • $ End of string

Regex demo

  • Related