Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a url from last slash using regex?

Tags:

regex

I want to split a url into two from last /, for example:

http://github.com/members into http://github.com and members

So far I have tried https://regex101.com/r/SiVvRA/1, which just gives me the second part. Any pointers?

like image 386
Vishal Avatar asked Nov 30 '25 15:11

Vishal


2 Answers

To split on the last slash, split on slash not followed by another slash, using this regex:

/(?!.*/)

See live demo of this regex matching the last slash

See live demo of this regex being used in this Java to split:

String url = "http://github.com/members";
String[] parts = url.split("/(?!.*/)");
Arrays.stream(parts).forEach(System.out::println);

Output:

http://github.com
members
like image 193
Bohemian Avatar answered Dec 02 '25 05:12

Bohemian


Depending what language you are using, you may simply use a built in split method; But for a regex solution, you can match the string into two groups and extract them accordingly:

^(.*)/([^/]*)$

https://regex101.com/r/SiVvRA/2

like image 35
Psidom Avatar answered Dec 02 '25 03:12

Psidom



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!