1

I have some uris which I want to extract parameters if they are exist, I come up with this code. Can someone point me to fix regex to success.

cityId and countryId works as expected but Cant get only numbers after word '-a-'

Regex

// "/city/berlin-a-10284?cityId=123456&countryId=4545"
// "/city/berlin-a-10284"
// "/city/berlin-a-10284?cityId=123456"
// "/city/berlin-a-10284?countryId=4545"



private String ValueExtractor(String url, String searchWord) {

        String regex = "(?<=" + searchWord + ").*?(?=&|$)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(url);

        return matcher.find() ? matcher.group() : "";
}


String productId = "";
String cityId = "";
String countryId = "";

if (url.contains("-p-")) {
    productId = ValueExtractor(url, "-a-");
}

if (url.contains("cityId")) {
    cityId = ValueExtractor(url, "cityId=");

}

if (url.contains("countryId")) {
    countryId = ValueExtractor(url, "countryId=");

}

Expected results:

"/city/berlin-a-10284?cityId=123456&countryId=4545" 
productId:10284
cityId: 123456
countryId: 4545

"/city/berlin-a-10284"
productId:10284

"/city/berlin-a-10284?cityId=123456"
productId:10284
cityId: 123456

"/city/berlin-a-10284?countryId=4545"
productId:10284
countryId: 4545
1

1 Answer 1

1

Cant get only numbers after word '-a-'

You can use the regex, (?<=-a-)\d+(?=[?&]|$) to retrieve this number.

  • (?<=-a-)\d+ specifies one or more digits preceded by -a-.
  • (?=[?&]|$) specifies positive lookahead for ?, or & or end of line.
Sign up to request clarification or add additional context in comments.

4 Comments

But regex seems like a poor tool for parsing URIs. Wouldn't using the URI class be better?
@markspace - URI classes would definitely be better if the full path or parameters are to be extracted. In this particular case, the OP is looking to get a part of the path.
The OP also has a query string attached to the path in some cases. I really think using URI for parsing the path and the query would be better.
@markspace - I respect your concern but I am being lazy to post another answer after getting tired of the whole day's work 😊. If you have time, please post an answer.

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.