Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Regular expression - parse version number string

807588Mar 5 2009 — edited Mar 5 2009
Hi,

I try to parse a string using regular expressions but id did not work correctly in all cases.
The string that i want to parse can have one of the following layout:
3.4.5.v20090305 or 
3.4.5
The first three parts have to be integer values, the last part can be a free string (which is optional).

I use the following code to parse the version number and extract the parts:
Pattern versionPattern = Pattern.compile("(\\d+)\\.{1}(\\d+)\\.{1}(\\d+)(?:\\.{1}(\\w+))?");
Matcher m = versionPattern.matcher(versionString);
if (!m.find()) {
    throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
}
// assert that we matched every part
// three groups (without qualifier) or four parts (with qualifier)
int groups = m.groupCount();
if (groups != 4) {
     throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
}
// extract the parts
major = parseInt(m.group(1));
minor = parseInt(m.group(2));
micro = parseInt(m.group(3));
qualifier = m.group(4);
The above regular expression works in all cases that i tested, except one.
The follwoing string is accepted as correct input: (but it shouldn't)
3.4.5a.v20090305
And i get the result:
major = 3
minor = 4
micro = 5
qualifier = a.v20090305

Thanks for help or suggestions :)

Best Regards,
Michael
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 2 2009
Added on Mar 5 2009
3 comments
2,703 views