regex removing filename from path
Asked Answered
A

3

11

How could I design a RegEx script which would remove a filename from a path? The trick is, the paths have all sorts of wrenches to throw into the works.

Paths can consist of:

1: "Folder1/Folder2/Folder3.1234/folder4.5678/ApplesandOranges.txt","MoreInfo","EvenMoreInfo"
2: "Folder1/Folder2/Folder3.1234/folder4.91011/","MoreInfo","EvenMoreInfo"

or even

3: "Folder1/Folder2/Folder3.1234/folder4.5678/ApplesandOranges.zip?CatsAndDogs.txt","MoreInfo","EvenMoreInfo"

In cases 1 and 3, I'd like to end up with:

Folder1/Folder2/Folder3.1234/folder4.5678/

though, it would be acceptable for the second to return as

Folder1/Folder2/Folder3.1234/folder4.5678/ApplesandOranges.zip

though not preferred.

In case 2, it'd just skip that line entirely as there is no filename.

Any suggestions?

Using standard RegEx via a text editor. No java use and such.

Note: The path is just an example. There could be 50 folders. It's not a mere 4 folders all of the time

Antipole answered 11/9, 2014 at 20:20 Comment(1)
What about s/.*\/(.*)/\1/?Swiss
K
21

You can use a simple regex like this:

(.*\/).*

Working demo

enter image description here

As you can see, the idea is to capture all the content to the last slash by using (.*\/) and discard the rest .*. Check the substitution section above.

Know answered 11/9, 2014 at 20:30 Comment(3)
Ah...that would work but you just made me realize another piece of the puzzle. Updating my original post to reflect.Antipole
Actually, you know what, I can work with your answer. I'll just split my data file into two parts. One with everything but filepath, and one with just filepath and use your fix. Thanks!Antipole
Fede, sadly, no. However, I've come up with a solution based on your answer. I'll be marking answered. I'd upvote if I had the rep to do it!Antipole
L
5

You can use this.

[^\/]+$

'$' matches the position at the end of the string while '[^/]+' matches any string that does not have any '/'.

Lavinalavine answered 13/11, 2018 at 12:8 Comment(0)
Y
1

What about this one?

@"^.*[\/]"

output result

Yogi answered 6/8, 2021 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.