3

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

i need to return the number 33445566778899 (with forward slashes removed, number is of variable length but between 10 & 20 digits)

Simple enough (or so i thought) except everything I've tried doesn't seem to work but why?

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

4 Answers 4

2

Try this one-liner:

String number = url.replaceAll(".*/(\\d{10,20})/.*", "$1");
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't there be a / after the number group as well (I noticed you added it before in an edit)? Otherwise it'd find the number in http://www.abc.com/alpha/beta/33445566778899xyz/gamma/delta which doesn't not seem to be expected.
@Gorkk yes, for ccompleteness it should be there. Thx.
0

This regex works -

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

Testing it-

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

Comments

0

Try,

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);

Output:

33445566778899

Comments

0

Instead of saying it "doesn't seem to work", you should have given use what it was returning. Testing it confirmed what I thought: your code would return 3 for this input.

This is simply because your regexp as written will capture a digit following a / and followed by 10 to 20 digits themselves followed by a /.

The regex you want is "/(\\d{10,20})/" (you don't need to escape the /). Below you'll find the code I tested this 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));
    }
}

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.