tags:

views:

25

answers:

2

Hey everyone,

I need a regex that will find everything in a string up to and including the last \ or /.

For example, c:\directory\file.txt should result in c:\directory\

Thanks!

+3  A: 

Try this: (Rubular)

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

Explanation:

^      Start of line/string
(      Start capturing group
.*     Match any character greedily
[\\\/] Match a backslash or a forward slash
)      End the capturing group  

The matched slash will be the last one because of the greediness of the .*.

If your language supports (or requires) it, you may wish to use a different delimiter than / for the regular expression so that you don't have to escape the forward-slash.

Also, if you are parsing file paths you will probably find that your language already has a library that does this. This would be better than using a regular expression.

Mark Byers
+1 for **...you will probably find that your language already has a library that does this...**
Carlos Muñoz
A: 

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

Domenic