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-'
// "/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
new URI( string ).getPath()would be a better start. docs.oracle.com/en/java/javase/16/docs/api/java.base/java/net/…