Reputation: 1356
I need to parse into a variable a certain part of a URI for a Spring filter I am writing. I am trying to extract out a username, which could be the last part of the URI, part of a more complex URI or contain query string parameters after the username.
Example inputs
In each case I would like to end up with a string containing "jay". Would simply using indexOf
be appropriate here, or is this better suited to a regex? I have limited experience with regular expressions in Java so any help is appreciated. Thanks!
Upvotes: 1
Views: 68
Reputation: 421030
To do this properly I suggest you use the URI
class.
URI users = URI.create("/users"); // Can be put as a final static field
URI uri = URI.create(uriString); // Can be skipped if you have a URI as input
String afterUsers = users.relativize(uri).getPath();
if (afterUsers.isEmpty())
System.out.println("No user");
else
System.out.println("User: " + afterUsers.split("/", 2)[0]);
Upvotes: 4