Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - 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 -.

question from:https://stackoverflow.com/questions/65918620/regex-is-working-on-chrome-but-not-in-safari

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...