0

I have wrote regular expression to accept following type of versions

  • "a.." ---> any version of "a"
  • "a.b.*" ---> any version of "a.b"
  • "a.b+" ---> "a.b" or later
  • "a.b.c+" ---> "a.b.c" or later

An example: "4.2.2+", "4.3.*, "4.2+"

/^([0-9])\.([0-9]+[*]{0,1}[+]?)(?:\.([0-9]+[*]{0,1}[+]?))?$/

It is accepting above all type but also accepting "4.2+.0" which should be invalid. How can I avoid this "4.2+.0" scenario.

Can anyone provide me regex to validate above versions?

0

2 Answers 2

1

Please use following regex for validating version /^\d+((?:.\d+([+]$){0,1})|(.[*]{1,1})){1,2}$/

^ Start of string \d+ Match 1+ digits

  1. (?:.\d+([+]$))+ Repeat matching 1 or more times . and 1+ digits if are you adding + then $ End of string. OR
  2. (?:.?[*])? Optionally match an optional dot * for one or two times $ End of string

Please check here

1

To match the examples with at least a single dot and an optional * or + at the end:

^\d+(?:\.\d+)+(?:\.?[+*])?$
  • ^ Start of string
  • \d+ Match 1+ digits
  • (?:\.\d+)+ Repeat matching 1 or more times . and 1+ digits
  • (?:\.?[+*])? Optionally match an optional dot and either * or +
  • $ End of string

See a regex demo.

To also match the examples without a dot you can change the plus to an asterix for the repeating group:

^\d+(?:\.\d+)*(?:\.?[+*])?$

See another regex demo.

Not the answer you're looking for? Browse other questions tagged or ask your own question.