简体   繁体   中英

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@domain-good.com
random@domain-bad-.com

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM