Simon
Simon

Reputation: 1731

Get last part of numbers from string

I am trying to get only the last part of numbers from a string using regex but somehow it only shows me the first part (1.2.54 /1.5 / 1.568).

Any help is appreciated.

Example strings could be:

1.2.54 (4587) //should result in 4587

1.5 b458 //should result in 458

1.568 build45 version6 //should result in 45 6

My method:

private static String getVersionAddition(String str) {
        String version = "";
        Pattern p = Pattern.compile("(([0-9])+(\\.{0,1}([0-9]))*)+");
        Matcher m = p.matcher(str);

        if (!m.find()) {
            Log.e("ERROR", str + " skipped");
        } else
            version = m.group();
        Log.e("VERSION", version);

        return version;
    }

Upvotes: 0

Views: 88

Answers (3)

Firoz Memon
Firoz Memon

Reputation: 4650

Use Pattern: (\d+)(?!.*\d)

Replace line:

Pattern p = Pattern.compile("(\\d+)(?!.*\\d)");

It Outputs:

1.2.54 (4587) -> 4587

1.5 b458 -> 458

1.568 build45 version6 -> 6

Upvotes: 0

l'L'l
l'L'l

Reputation: 47169

There's multiple ways to do this, although you should be able to get the remaining digits with:

^[0-9.\d\s]+[\D]*|([\d]+)

Then just reference match group 1 to get the results.

Example:

https://regex101.com/r/2TY8Eh/1

Upvotes: 0

Bek
Bek

Reputation: 8471

try this

public class Test {
public static void main(String args[]){
    String str1 = "1.2.54 (4587)";
    String str2 = "1.5 b458";
    String str3 = "1.568 build45 version6";
    str1 = str1.replaceAll("[^\\d.]", " ");
    str2 = str2.replaceAll("[^\\d.]", " ");
    str3 = str3.replaceAll("[^\\d.]", " ");
    System.out.println(str1.trim().substring(str1.trim().lastIndexOf(" ")+1));
    System.out.println(str2.trim().substring(str2.trim().lastIndexOf(" ")+1));
    System.out.println(str3.trim().substring(str3.trim().lastIndexOf(" ")+1));
}
}

Upvotes: 1

Related Questions