1

what is the regular expression to find the path param from the url?

http://localhost:8080/domain/v1/809pA8
https://localhost:8080/domain/v1/809pA8

Want to retrieve the value(809pA8) from the above URL using regular expression, java is preferable.

4

3 Answers 3

4

I would suggest you do something like

url.substring(url.lastIndexOf('/') + 1);

If you really prefer regexps, you could do

Matcher m = Pattern.compile("/([^/]+)$").matcher(url);

if (m.find())
    value = m.group(1);
Sign up to request clarification or add additional context in comments.

2 Comments

prefer regular expression.
Why? This problem isn't really complicated enough to require regular expressions.
1

I would try:

String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/'), url.length()-1));

No need for regex here, I think.

EDIT: I'm sorry I made a mistake:

String url = "http://localhost:8080/domain/v1/809pA8";
    String value = String.valueOf(url.subSequence(url.lastIndexOf('/')+1, url.length()));

See this code working here: https://ideone.com/E30ddC

3 Comments

This is wrong since the end index (second argument to subSequence) is exclusive. This solution misses the last character.
So, why use CharSequence.subSequence instead of String.substring? For String.substring the end index is optional (and you wouldn't have to use String.valueOf).
It's just a way of doing things, the answer before mine was about String substring, I think it's better to give another solution better than repeat the one given before.
0

For your simple case, regex is an overkill, as others noted. But, if you have more cases and this is why you prefer regex, give Spring's AntPathMatcher#extractUriTemplateVariables a look, if you're using Spring. It's actually better equipped for extracting path variables than regex directly. Here are some good examples.

Comments

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.