0

Trying to extract the id portion of the url string.

if(request.getPathInfo().matches("/products/(.*?)")) {
    // use the id portion
    // request.getPathInfo().split("/")[2] // simple attempt
} else if(request.getPathInfo().matches("/orders/(.*?)")) {
    // use the id 
}

Example string

/products/5d3abb1c30431b78fcf02290
/orders/5d3abb1c30431b78fcf01192

Edit

Attempt

Matcher m = Pattern.compile("/users/(.*?)").matcher(request.getPathInfo());

if(m.find()) {
    System.out.println(m.group(0)); // /users/
    System.out.println(m.group(1)); // empty string or null
} else {
    System.out.println("not found");
}
AppDeveloper
  • 1,816
  • 7
  • 24
  • 49
  • 2
    Possible duplicate of [Using Regular Expressions to Extract a Value in Java](https://stackoverflow.com/questions/237061/using-regular-expressions-to-extract-a-value-in-java) –  Jul 26 '19 at 10:09
  • sorry not a duplicated, i need help, something wrong with this regex, it's not picking up, `group(0)` returns `/users/` but `group(1)` returns empty – AppDeveloper Jul 26 '19 at 10:18
  • 1
    What's the `?` for, in your regex? – Lyuboslav Jul 26 '19 at 10:28
  • want to match any string, for instance an identifier like `5d3abb1c30431b78fcf02290` – AppDeveloper Jul 26 '19 at 10:29
  • thanks for the pointer, it's working without `?` – AppDeveloper Jul 26 '19 at 10:33
  • on a side note, can someone suggest an efficient way for multiple urls, let's say if I match `/users` I don't need to match `/orders` and vice versa, an efficient branching structure please? – AppDeveloper Jul 26 '19 at 10:34

0 Answers0