0Day Forums
Regular Expression, remove everything after last forward slash - Printable Version

+- 0Day Forums (https://zeroday.vip)
+-- Forum: Coding (https://zeroday.vip/Forum-Coding)
+--- Forum: PowerShell & .ps1 (https://zeroday.vip/Forum-PowerShell-ps1)
+--- Thread: Regular Expression, remove everything after last forward slash (/Thread-Regular-Expression-remove-everything-after-last-forward-slash)



Regular Expression, remove everything after last forward slash - norland174 - 07-21-2023

I'm trying to use a regular expression within PowerShell to remove everything from the last slash in this string;

NorthWind.ac.uk/Users/Current/IT/Surname, FirstName
NorthWind.ac.uk/Users/Dormant/DifferentArea/Surname, FirstName

I need to remove Surname, FirstName including the /.
The string should look like this.

NorthWind.ac.uk/Users/Current/IT

If someone could help me, I would be very grateful.

I have tried this; ` -replace '([/])$',''` but I can't seem to get it to work.

Thanks



RE: Regular Expression, remove everything after last forward slash - Sirruntinesses337 - 07-21-2023

Replace `/[^/]*$` with an empty string


RE: Regular Expression, remove everything after last forward slash - nestarckdag - 07-21-2023

check this regex

[To see links please register here]

?2vhll
i can't test it on powershell but it work in the regex generator

/(?!.*/).*


RE: Regular Expression, remove everything after last forward slash - oswaldifwknuhr - 07-21-2023

Here's a solution that doesn't require regular expressions:

PS> $cn = 'NorthWind.ac.uk/Users/Current/IT/Surname, FirstName' -split '/'
PS> $cn[0..($cn.count-2)] -join '/'
NorthWind.ac.uk/Users/Current/IT


RE: Regular Expression, remove everything after last forward slash - Mrnoncontagiousness304 - 07-21-2023

Here's another solution that doesn't require regular expressions:

Take a substring of your string starting at the beginning of the string and ending before the index of the last slash in your string:

PS> $indexoflastslash = ("NorthWind.ac.uk/Users/Current/IT/Surname, FirstName").lastindexof('/')
PS> "NorthWind.ac.uk/Users/Current/IT/Surname, FirstName".substring(0,$indexoflastslash)






RE: Regular Expression, remove everything after last forward slash - vkamooro508 - 07-21-2023

This solution doesn't use regexes.
I believe this approach is probably easier to understand, after all regexes - in general - are hard to read:

`NorthWind.ac.uk/Users/Current/IT/Surname, FirstName` has a path-like structure (windows also supports the forward slash as a path separator), so we could use split-path to return the parent 'directory' path.

Because '\' is the default path separator, we need to replace the '\' with '/' after doing this:

(split-path NorthWind.ac.uk/Users/Current/IT/Surname, FirstName).replace('\','/')
# will return NorthWind.ac.uk/Users/Current/IT