Extracting a number from a URL in Java via Regex

Take url http://www.abc.com/alpha/beta/33445566778899/gamma/delta

I need to return a number 33445566778899(with a slash removed, the number has a variable length, but from 10 to 20 digits)

Simple enough (or so I thought), except that what I tried seems to not work, but why?

Pattern pattern = Pattern.compile("\\/([0-9])\\d{10,20}\\/");
        Matcher matcher = pattern.matcher(fullUrl);
        if (matcher.find()) {
            return matcher.group(1);
        }
+3
source share
4 answers

Try using one layer:

String number = url.replaceAll(".*/(\\d{10,20})/.*", "$1");
+1
source

This regex works -

"\\/(\\d{10,20})\\/"

Testing -

String fullUrl = "http://www.abc.com/alpha/beta/33445566778899/gamma/delta";
Pattern pattern = Pattern.compile("\\/(\\d{10,20})\\/");
Matcher matcher = pattern.matcher(fullUrl);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

OUTPUT - 33445566778899

0
source

,

String url = "http://www.abc.com/alpha/beta/33445566778899/gamma/delta";
String digitStr = null;
for(String str : url.split("/")){
    System.out.println(str);
    if(str.matches("[0-9]{10,20}")){
        digitStr = str;
        break;
    }
}
System.out.println(digitStr);

:

33445566778899
0

, , ", ", , . , : 3 .

, , , , /, 10 20 , /.

You want to use regex "/(\\d{10,20})/"(you don't need to exit /). Below you will find the code that I tested with.

public static void main(String[] args) {
    String src = "http://www.abc.com/alpha/beta/33445566778899/gamma/delta";
    Pattern pattern = Pattern.compile("/(\\d{10,20})/");
    Matcher matcher = pattern.matcher(src);
    if (matcher.find()) {
        System.out.println(matcher.group(1));
    }
}
0
source

All Articles