2

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?

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If the digits are always at the end of the string, you don't need a lookahead.
0

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.

2 Comments

This solution will also find the case /me/500/hello --> 500.
in this case I do not need to find it
0
    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).

Comments

0

try this regex

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

the first capturing group is your number.

sample

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.