Regex for extracting digits in version format

Viewed 53

I am going to extract numbers from a string. Numbers represents a version. It means, I am going to match numbers which are between:

  • _ and /
  • / and /

I have prepared the following regex, but it doesn't work as expected:

.*[\/_](\d{1,2}[.]\d{1,2}[.]\d{1,2})\/.*

For the following example, the regex should match twice:

Input: name_1.1.1/9.10.0/abc. Expected result: 1.1.1 and 9.10.0 , but my regex returns only 9.10.0, 1.1.1 is omitted. Do you have any idea what is wrong?

3 Answers

You could just split the string on _ or /, and then retain components which appear to be versions:

List<String> versions = new ArrayList<>();
String input = "name_1.1.1/9.10.0/abc";
String[] parts = input.split("[_/]");
for (String part : parts) {
    if (part.matches("\\d+(?:\\.\\d+)*")) {
        versions.add(part);
    }
}

System.out.println(versions);  // [1.1.1, 9.10.0]

You can assert the / at the end instead of matching it, and omit the .*

Note that you don't have to escape the /

[/_](\d{1,2}[.]\d{1,2}[.]\d{1,2})(?=/)

Regex demo | Java demo

Example code

String regex = "[/_](\\d{1,2}[.]\\d{1,2}[.]\\d{1,2})(?=/)";
String string = "name_1.1.1/9.10.0/abc";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Output

1.1.1
9.10.0

Another option could be using a positive lookbehind to assert either a / or _ to the left, and get a match only.

(?<=[/_])\d{1,2}[.]\d{1,2}[.]\d{1,2}(?=/)

regex demo

Code Demo

        String regex = "(\\d+.\\d+.\\d+)";
        String string = "name_1.1.1/9.10.0/abc";
        String string2 = "randomversion4.5.6/09.7.8_9.88.9";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(string);
        Matcher matcher2 = pattern.matcher(string2);
        
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }


        while (matcher2.find()) {
            System.out.println(matcher2.group(1));
        }

Out:

1.1.1
9.10.0
4.5.6
09.7.8
9.88.9

Just write regex for what you want to match. In this case just the version number.

Regex can be used to match whole strings or to find if there is a substring that exists in a string.

When using regex to find a substring, you cannot always match all filenames or any string. Hence only match on what you want to find. This way you can find the versions no matter what string it is in.

Related