java regex to extract the password from url path between the last 2 slashes

2658 views java
3

how can i extract the password form the following links using java code:

it's one link and comes each time with different structure. the password is always between the last 2 slashes.

http://example.com:8080/files/user1/password123/12351.png
http://example.com:8080/user1/password123/956253.png
http://example.com:8080/user1/password123/3652

i need to get the password: password123

currently i use:

String url = "http://example.com:8080/files/user1/password123/12351.png";
String[] split = url .split("/");
//i reverse the array
String[] temp = new String[split.length];
for(int i = split.length - 1; i > -1; i --){
        temp[split.length - i -1] = split[i];
}
split = temp;
String password = split[1];

but this depends on the index of array.

is there a regex code to do so?

regards

answered question

will the password always be second last component of the URL?

yes : the password always be second last component of the URL

1 Answer

9

If the structure of your data is always like that and password is always the between the last 2 slashes you could just use split and use the length of the array minus 2.

Apart from verifying that the index exists etc, you might use:

String url = "http://example.com:8080/files/user1/password123/12351.png";
String[] split = url .split("/");        
System.out.println(split[split.length - 2]);

posted this

Have an answer?

JD

Please login first before posting an answer.