1

I have to validate version number pattern for following examples:

A1
aabc1
AabC134
aabc12.2
aA1.2.3
0.1.1
0.0.2
a.b.c
a.1.2
a.0.0
1.0.0
1.0
1

Basically it should allow alphanum in all three parts (split parts by dot) but it cannot be:

0
0.0.0
000.000.000
0000.00.00

I have tried this regex but it allows zeros:

/([A-Za-z\d]+)?(.*[A-Za-z\d]+)?(.*[A-Za-z\d]+)$

Can it be modified to achieve above results?

4
  • /^(?![0.]+$)[A-Za-z0-9]+(?:\.[A-Za-z0-9]+){0,2}$/, see this demo. Commented Jul 15, 2019 at 15:29
  • @WiktorStribiżew It still allows 0 and 0.0.0 etc Commented Jul 15, 2019 at 15:31
  • No, it does not. Check regex101.com/r/w3pMUl/2 Commented Jul 15, 2019 at 15:31
  • @WiktorStribiżew Yes now it doesn't. Commented Jul 15, 2019 at 15:32

2 Answers 2

2

I might just use negative lookaheads to assert that the blacklisted version numbers do not appear, and otherwise proceed along the lines of what you are already doing:

 ^(?!^(?:0|0\.0\.0|000\.000\.000|0000\.00\.00)$)[A-Za-z0-9]+(?:\.[A-Za-z0-9]+){0,2}$

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You may use

/^(?![0.]+$)[A-Za-z0-9]+(?:\.[A-Za-z0-9]+){0,2}$/

Or,

/^(?![0.]+$)[A-Z\d]+(?:\.[A-Z\d]+){0,2}$/i

See the regex demo

Details

  • ^ - start of string
  • (?![0.]+$) - no just zeros / dots till the end of string
  • [A-Za-z0-9]+ - one or more digits/letters
  • (?:\.[A-Za-z0-9]+){0,2} - 0, 1 or 2 repetitions of . and 1+ digits or letters
  • $ - end of string

Regex graph:

enter image description here

2 Comments

That's Perfect for my scenario! Thanks Wiktor Stribiżew
While your answer may be streamlined and correct, were this regex to appear inside some application code, I would much rather see a plain sight blacklist of version numbers. Imagine if you move on, and someone else inherits your code. Would that person be able to figure out that (?![0.]+$) were intended to block the four version numbers given in the OP?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.