antohoho
antohoho

Reputation: 1020

Extract numbers from a string Java

I have string that looks like a url. For example:

.com/ - finds nothing
.com - finds nothing
/me - finds nothing
/me/ - finds nothing
/me/500/hello - finds nothing
/me/12/test/550        - I need find 550
/test/1500             - I need find 1500
/test/1500/            - I need find 1500

I need to extract always last digits, right now I do it this way

int index = url.lastIndexOf('/');
String found = url.substring(index + 1, url.length());
if(Pattern.matches("\\d+", found)) {
 // If found digits at the end doSometihng
}

However I do not like this solution, and it does not work if I have slash at the end. What would be nice solution to catch last digits?

Upvotes: 2

Views: 700

Answers (4)

1010
1010

Reputation: 1848

try this regex

.*\/(\d+)\/?

the first capturing group is your number.

sample

Upvotes: 0

Sigismundus
Sigismundus

Reputation: 625

A number is last if it is not followed by any other number. In regex:

public static void findLastNumber() {
  String str = "/me/12/test/550/";
  Pattern p = Pattern.compile("(\\d+)(?!.*\\d)");
  Matcher m = p.matcher(str);
  if (m.find()) {
    System.out.println("Found : " + m.group());
  }
}

You can test this regular expression here.

Upvotes: 2

Al Wang
Al Wang

Reputation: 354

    String text = "/test/250/1900/1500/";
    Pattern pattern = Pattern.compile("^(.*)[^\\d](\\d+)(.*?)$");
    Matcher matcher = pattern.matcher(text);
    if(matcher.find()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
        System.out.println(matcher.group(3));
        System.out.println("true");
    } else {
        System.out.println("False");
    }

The output is:

/test/250/1900
1500
/

You'll want to grab group(2).

Upvotes: 0

vinntec
vinntec

Reputation: 495

I believe the following code does what you need:

public Integer findLastInteger(String url) {
  Scanner scanner = new Scanner(url);
  Integer out = null;
  while(scanner.hasNextInt())
    out = scanner.nextInt();
  return out;
}

This code returns your last integer if there is any, and returns null if there isn't.

Upvotes: 0

Related Questions