Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex is working on Chrome but not in Safari

The following regex is working just fine on Chrome, but it breaks in Safari with the following error: SyntaxError: Invalid regular expression: invalid group specifier name.

Regex: /^[a-zA-Z0-9.!#$%&'*+\-\/=?^_{|}~]+[@](?!-)[a-zA-Z0-9-]+(?<!-)[.][a-zA-Z]{2,}$/

I am new at Regex, so I have no idea why it seems to work on 1 browser but not the other, is there anyway I can fix this?

Example Data:

random#[email protected]
[email protected]

The 2 example should fail because it starts/ends with a -.

like image 443
James Perrone Avatar asked Oct 22 '25 02:10

James Perrone


1 Answers

Your pattern contains a lookbehind and Safari does not support lookbehinds yet. Actually, the (?!-)[a-zA-Z0-9-]+(?<!-) pattern means to match one or more alphanumeric or hyphen chars while forbidding - to appear at the start and end of this sequence. It is simple to refactor this pattern part to [a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*.

So, the regex will look like

/^[a-zA-Z0-9.!#$%&'*+\-\/=?^_{|}~]+@[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/

[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)* matches one or more alphanumeric chars and then any zero or more sequences of a hyphen followed with one or more alphanumeric chars.

Note you may simply use @ instead of [@] as @ is never special in any regex, and [.] can be written as \., which means a literal dot.

like image 163
Wiktor Stribiżew Avatar answered Oct 23 '25 16:10

Wiktor Stribiżew