Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for everything before last forward or backward slash

Tags:

regex

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\

like image 443
maveric19 Avatar asked Oct 20 '10 20:10

maveric19


People also ask

How do you handle forward slash in regex?

The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.

What does \\ mean in regular expression?

You also need to use regex \\ to match "\" (back-slash). Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does \b represent in regex?

Simply put: \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b. A “word character” is a character that can be used to form words. All characters that are not “word characters” are “non-word characters”.


3 Answers

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.

like image 75
Mark Byers Avatar answered Oct 13 '22 04:10

Mark Byers


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

like image 45
Domenic Avatar answered Oct 13 '22 04:10

Domenic


If you're using sed for example, you could do this to output everything before the last slash:

echo "/home/me/documents/morestuff/before_last/last" | sed s:/[^/]*$::

It will output:

/home/me/documents/morestuff/before_last
like image 1
Emil Avatar answered Oct 13 '22 05:10

Emil