orange88
orange88

Reputation: 81

regular expression to match string upto the last occurrence of “/”

I was wondering if anyone knows how to form a regular expression that would help match utp the last occurrence of a slashed file path like:

fred/george/simpson/kill should get result --> fred/george/simpson/

abc/def/ghi/..v/file.jpg should get result --> abc/def/ghi/..v/

Any advice would be appreciated.

THANKS FOR THE REPLIES ACTUALLY ID like to reframe the question , im not sure if I should start this as a new thread....I actually need to match everything between two '/' in a regex for example: tom/jack/sam/jill/ ---> I need to match jill

and in that case also need to match tom/jack/sam (without the last '/')

Thoughts appreciated!

Upvotes: 0

Views: 2535

Answers (5)

nes1983
nes1983

Reputation: 15756

Regexs aren't for everyone. Rob Pike warns of them with reason.

(.*\/).*\/$

That being said, the above (untested!) will match what you want in capture group 1.

Let me remind you: better think long and hard why you want to use capture groups, even though you don't understand them. bsd's answer is clearly better.

Upvotes: 0

bsd
bsd

Reputation: 2717

You should probably do it without regular expression. Simply find the rightmost / and slice it from there.

file = 'fred/george/simpson/kill'
last_slash = file.rindex('/')
parent_file = file[0..last_slash] if last_slash

=>fred/george/simpson/

Upvotes: 1

Sergio
Sergio

Reputation: 6948

Try this regex:

((?<=/).[^/]*?)$

And replcae matched with '' ;

Upvotes: 0

falsetru
falsetru

Reputation: 368954

Use [^\/]*$ as pattern:

'fred/george/simpson/kill'.sub(/[^\/]*$/, '') => "fred/george/simpson/"
'abc/def/ghi/..v/file.jpg'.sub(/[^\/]*$/, '') => "abc/def/ghi/..v/"

Upvotes: 0

Chris Heald
Chris Heald

Reputation: 62648

You can probably just use File.dirname here.

> File.dirname("fred/george/simpson/kill")
=> "fred/george/simpson"
> File.dirname("abc/def/ghi/..v/file.jpg")
=> "abc/def/ghi/..v"

You can then append a trailing slash if you need.

Upvotes: 3

Related Questions