user3157090
user3157090

Reputation: 537

find the path param using regex in the url

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.

Upvotes: 1

Views: 3393

Answers (3)

Fourat
Fourat

Reputation: 2447

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

Upvotes: 1

kaqqao
kaqqao

Reputation: 15429

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.

Upvotes: 0

aioobe
aioobe

Reputation: 420971

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);

Upvotes: 4

Related Questions