Regular expression for application version Only these formats are accepted.


1.1.1
1.1.1-r
1.1.1-b
1.1.1-r1
1.1.1-b1


I wrote this code. What don't I like in it? I used parentheses and now I have two groups. In fact, I don't need to do anything with groups. And there might be some bugs as well.

package com.sandbox;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
/**
 * @param args
 */
public static void main(String[] args) {
    checkVersion("10.22.5-r");
}

private static void checkVersion(String current) {
    String regex = "([1-9]\\d*)\\.(\\d+)\\.(\\d+)-[b|r](?:[1-9]\\d*)*";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcherCurrent = pattern.matcher(current);
    System.out.println("Matches: " + matcherCurrent.matches());
    System.out.println("The first digit: " + matcherCurrent.group(1));
    System.out.println("The second digit: " + matcherCurrent.group(2));
    System.out.println("The third digit: " + matcherCurrent.group(3));

    // Compare and decide whether an update is necessary
}


}

Thank you for the answers you give me. I'll vote up as soon as I have enough reputation.
It seems to me that you're using * when it looks like that's not the behaviour you want.

i.e. this bit -(b|r)* do you really mean a dash followed by either a 'b' or an 'r' zero or more times? I think it's more likely that you meant more along the lines of: there can be a dash followed by a 'b' or an 'r' but there doesn't have to be.

Do you want 1.1.1-brrrrrrrrrrr1 to match? What's the goal of the regex, is it just to see if it fits the pattern or do you want to use it to get the various numbers out?

Btw: If you don't care about groups you can use (?: ) instead of () to create non capturing groups.

Edit:

I think your regex needs to be more like: ^([1-9]\\d*)\\.(\\d+)\\.(\\d+)(?:-[br]{1}[0-9]?\\d*)?$ This makes everything following the first 3 numbers optional.

I do wonder whether a regex is the right option though... If you know the strings you are comparing are definitely well formed version numbers just do normal string manipulation.

// Pseudocode
String versionNumber = "1.1.1-r1";
int indexOfDash = versionNumber.indexOf("-");
if (indexOfDash != -1) 
{
    versionNumber = versionNumber.substring(0, indexOfDash);
}
String[] numbers = versionNumber.split(".");

// Now compare your numbers.


I generally like to avoid regular expressions as they are a lot more difficult to get right than people give them credit for. However, if you also need to check that it is a well formed version number you probably want to use the regex option.

In fact, I got the regex wrong - edited now. I changed the matching for the final part of the version number and added in the anchors.