2

I want to write a regular expression which will take the characters from the last "slash" "/" to the right.

Exemple1 : http:// thesite.com/tester/blabla/this_is_the.jpg - I want to extract only the "this_is_the.jpg" Exemple2 : http:// thesite.com/tester/blabla/this_is_2.jpg - Only the "this_is_2.jpg"

vezeCS
  • 111
  • 1
  • 1
  • 11

4 Answers4

6

It's as simple as:

[^/]+$

Which basically says: "give me all characters at the end that are not slashes".

Example:

$ echo 'http:// thesite.com/tester/blabla/this_is_the.jpg' | egrep -o '[^/]+$'
this_is_the.jpg
xaizek
  • 4,575
  • 1
  • 24
  • 48
2

short answer:

/[^\/]*$/

explaination

$ match end of the string
[^\/] any character except /
* any number of things matched by previous token

a user
  • 20,998
  • 4
  • 53
  • 83
1

Here it is using sed:

sed 's#.*/\([^/]*\)$#\1#'
unxnut
  • 7,506
  • 2
  • 23
  • 36
0

I would anchor it on the extension, personally - then your validating that all in one go.

"/bla bala/this_is_the.jpg" 

\/([^\/]+\.jpg)$ 
Array
(
    [0] => /this_is_the.jpg
    [1] => this_is_the.jpg
) 

for other file types

\/([^\/]+\.(jpg|png|bmp))$

Array
(
    [0] => /this_is_the.jpg
    [1] => this_is_the.jpg
    [2] => jpg
)

for the other guys ( cant comment yet ) I would avoid the * and go with +, do you really want it to match on this "/bla bala/this_is_the/" ~ no file

ArtisticPhoenix
  • 20,683
  • 2
  • 18
  • 34