Search code examples
regexsemantic-versioning

How to validate version to accept 4.4+ but not 4.4+.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?


Solution

  • 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