Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

regex - Javascript conditional regular expression if-then-else

I'm trying to limit the entries to a specific format.

If the entry has 5500 or 5100 such as 011-5500-000-00 then I want to have this:

^[0-9]{2,}\[0-9]{2}-[0-9]{4}-[0-9]{3}-$

But if the entry has anything other than 5500 or 5100 I want to have this:

^[0-9]{2,}\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2}$

How can this be accomplished with the if then else idea?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Conditional regex syntax is not supported by JavaScript regex engine, but it can be worked around with a non-capturing group containing 2 alternatives:

  1. One with the positive look-ahead and

  2. The second with the reversed, negative look-ahead.

This regex meets your criteria and is JavaScript compatible:

^(?:(?=.*5[15]00)[0-9]{2,}\[0-9]{2}-[0-9]{4}-[0-9]{3}-|(?!.*5[15]00)[0-9]{2,}\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2})$

See regex demo

Let me break it down:

  • ^ - Start of string
  • (?:
    • (?=.*5[15]00)[0-9]{2,}\[0-9]{2}-[0-9]{4}-[0-9]{3}- - First alternative with the (?=.*5[15]00) look-ahead that requires a whole word 5500 or 5100 inside the string, and the first pattern you have
    • | - alternation operator
    • (?!.*5[15]00)[0-9]{2,}\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2}) - Second alternative that is prepended with the (?!.*5[15]00) negative look-ahead that makes sure there is no 5100 or 5500 inside the string, and only then matches your second pattern.
  • $ - end of string.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...