2
\$\begingroup\$

I develop an application which installs updates. These updates have a version id (this version id is created as a part of the application and the format is a fixed requirement) and I use a regex to parse/validate their id. Each group must be separated by a dot. The id must have 2 digits in the first group, one or two digits in the second group and the third group and at least one digit in the last group.

The regex I use is the following:

^[0-9]{2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,}$

regex in use

The regex works like expected but when I look at it I have a feeling telling me that I can make it better, smarter and and and and ...

Should I stay with this solution or how would you make it better?

The regex should work with the .NET-Framework Regex class.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ What kind of version number are you parsing? is this some kind of version number you have created? Or are you trying to parse something like semver? Its going to be difficult to answer without knowing the requirements. Also, could you please include your regex in the question instead of embedded in an image? Thanks. \$\endgroup\$
    – Dan
    Commented Oct 23, 2015 at 7:55
  • \$\begingroup\$ I've edited my post \$\endgroup\$
    – seveves
    Commented Oct 23, 2015 at 8:17

1 Answer 1

1
\$\begingroup\$

Since the second and third segment are similar, you can put them in a non-capturing group with quantifier.

If you allow/want the first digit to be \$ 0 \$ in your first group, the expression is ok as it is. Otherwise, you can restrict the first digit to be [1-9].

You can have + quantifier instead of {1,} as they are essentially the same :)

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

and for unpadded version matches:

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

Your Answer

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

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