Regular Expression to collect everything after the last /

Solution 1:

This matches at least one of (anything not a slash) followed by end of the string:

[^/]+$


Notes:

  • No parens because it doesn't need any groups - result goes into group 0 (the match itself).
  • Uses + (instead of *) so that if the last character is a slash it fails to match (rather than matching empty string).


But, most likely a faster and simpler solution is to use your language's built-in string list processing functionality - i.e. ListLast( Text , '/' ) or equivalent function.

For PHP, the closest function is strrchr which works like this:

strrchr( Text , '/' )

This includes the slash in the results - as per Teddy's comment below, you can remove the slash with substr:

substr( strrchr( Text, '/' ), 1 );

Solution 2:

Generally:

/([^/]*)$

The data you want would then be the match of the first group.


Edit   Since you’re using PHP, you could also use strrchr that’s returning everything from the last occurence of a character in a string up to the end. Or you could use a combination of strrpos and substr, first find the position of the last occurence and then get the substring from that position up to the end. Or explode and array_pop, split the string at the / and get just the last part.

Solution 3:

You can also get the "filename", or the last part, with the basename function.

<?php
$url = 'http://spreadsheets.google.com/feeds/spreadsheets/p1f3JYcCu_cb0i0JYuCu123';

echo basename($url); // "p1f3JYcCu_cb0i0JYuCu123"

On my box I could just pass the full URL. It's possible you might need to strip off http:/ from the front.

Basename and dirname are great for moving through anything that looks like a unix filepath.

Solution 4:

/^.*\/(.*)$/

^ = start of the row

.*\/ = greedy match to last occurance to / from start of the row

(.*) = group of everything that comes after the last occurance of /