Regular expression extracting a string from url

Viewed 475

What I am trying is to extract my account id from a url for other validations. see my URL samples.

http://localhost:8024/accounts/u8m21ercgelj/
http://localhost:8024/accounts/u8m21ercgelj
http://localhost:8024/accounts/u8m21ercgelj/users?

What I required is to extract u8m21ercgelj from the url. I tried it with below code but it fails for the cases like http://localhost:8024/accounts/u8m21ercgelj i.e with out a / at the end.

public  String extractAccountIdFromURL(String url) {
        String accountId = null;
        if ( url.contains("accounts")) {
            Pattern pattern = Pattern.compile("[accounts]/(.*?)/");
            Matcher matcher = pattern.matcher(url);
            while (matcher.find()) {

                accountId = matcher.group(1);
            }
        }
        return accountId;
    }

Can any one help me?

2 Answers
Related