0

I have a multiple string urls, from which i have to pick last few characters, which are id's infact. But the problem is that, the length of id's is not consistent, i.e., if one id is of length 6 then, other may be of length 5 or 4 and so on. The sample urls are like:

www.abc.com/xyz-123456
www.abc.com/pqr-5432
www.abc.com/lmn/opqr-25647

it could have been a lot easier if the length of the particular id portion would have been same, i could have used:

String abc = "www.abc.com/xyz-123456"; 
String id = abc.substring(abc.length()-6);

But now the scenario is different as length of id portion in the selected url is not the same always, How can i cater this varying id..???? please any help is appreciated.

5 Answers 5

5

There is a lastIndexOf method on the String object that will let you find the position of the '-' (I take it that is your separator). From there you can do the substring.

Sign up to request clarification or add additional context in comments.

2 Comments

@Pimastar, Thanks man, u have pulled me out of hell indeed...:P
Yes! Sure, i was trying but i am getting a message that i can accept answer in few minutes. So as the time passes, i'll accept that...:-)
2

You can use something like this.

String id=abc.subString(abc.lastIndexOf('\'),abc.length()-1);

Hope it will help you. :)

Comments

1
String url1 = "www.abc.com/xyz-123456";
String[] url1Split = url1.split("-");

What you're looking for can be found in url1split[1]

Comments

0

Use regex to remove all characters upto -.

String id = url.replaceAll("^.*-",""); 

or

String id = url.replaceAll("^.*-(\\w+)$","$1");

Comments

0

You can use LastIndexOf or create the regular expression.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.