Regular Expression to collect everything after the last /


I'm new at regular expressions and wonder how to phrase one that collects everything after the last /.

I'm extracting an ID used by Google's GData.

my example string is

Where the ID is: p1f3JYcCu_cb0i0JYuCu123

Oh and I'm using PHP.

6/13/2012 7:01:21 PM

Accepted Answer

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



  • 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 );
6/13/2012 11:13:31 PM



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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow