Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim/cut string in java by symbol?

Tags:

java

string

regex

I'm working on a project where my API returns url with id at the end of it and I want to extract it to be used in another function. Here's example url:

 String advertiserUrl = http://../../.../uuid/advertisers/4 <<< this is the ID i want to extract.

At the moment I'm using java's string function called substring() but this not the best approach as IDs could become 3 digit numbers and I would only get part of it. Heres my current approach:

String id = advertiserUrl.substring(advertiserUrl.length()-1,advertiserUrl.length());
System.out.println(id) //4

It works in this case but if id would be e.g "123" I would only get it as "3" after using substring, so my question is: is there a way to cut/trim string using dashes "/"? lets say theres 5 / in my current url so the string would get cut off after it detects fifth dash? Also any other sensible approach would be helpful too. Thanks.

P.s uuid in url may vary in length too

like image 917
Tomas Avatar asked Dec 14 '25 05:12

Tomas


1 Answers

You don't need to use regular expressions for this.

Use String#lastIndexOf along with substring instead:

String advertiserUrl = "http://../../.../uuid/advertisers/4";// <<< this is the ID i want to extract.
// this implies your URLs always end with "/[some value of undefined length]". 
// Other formats might throw exception or yield unexpected results
System.out.println(advertiserUrl.substring(advertiserUrl.lastIndexOf("/") + 1));

Output

4

Update

To find the uuid value, you can use regular expressions:

String advertiserUrl = "http://111.111.11.111:1111/api/ppppp/2f5d1a31-878a-438b-a03b-e9f51076074a/adver‌​tisers/9";
//                           | preceded by "/"
//                           |     | any non-"/" character, reluctantly quantified
//                           |     |     | followed by "/advertisers"
Pattern p = Pattern.compile("(?<=/)[^/]+?(?=/adver‌​tisers)");
Matcher m = p.matcher(advertiserUrl);
if (m.find()) {
    System.out.println(m.group());
}

Output

2f5d1a31-878a-438b-a03b-e9f51076074a

like image 194
Mena Avatar answered Dec 15 '25 19:12

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!