Lookbehind works in Chrome, but breaks in Safari: Invalid regular expression invalid group

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

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

Upvotes: 2

Views: 424

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

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

Upvotes: 1

bobble bubble
bobble bubble

Reputation: 18515

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.

Upvotes: 3

Related Questions