How to match slashes globally in regex except if it is at the start of the string

Viewed 56

Hello stackoverflowers,

i couldn't figure the solution out by myself and couldn't find a related answer so i seek your help :)

I'm working in a VB.Net 4.x environment where i usualy have to join windows styled paths from various sources that are very unreliable in its format (leading slashes, ending slashes, sometimes double slashes inside) hence i can't use Path.Join

My next best guess is to regex replace any double occurance of a backward slash with a single one: \\+

which is too naive, as it also converts a server adress which starts with a leading double backslash.

pseudocode

"\\server123\\a\\b\\\c\\".replace(/\\+/g, "\") -> "\server123\a\b\c"

thats a problem. i want to exclude any leading backslashes from matching. So i though i negative lookahead it:

regex

(?!^\\+)\\+

which would work in my example. But it does not what i want it to do. It matches the second backslash slash and replaces it.

What is wrong with my second regex? how do i negative lookahead something at the start.

Thanks for any explanation and solution

1 Answers

You can use

Regex.Replace(text, "(?<!^\\*)\\+", "\")

See the .NET regex demo and the VB.NET online demo.

Details:

  • (?<!^\\*) - a negative lookbehind that fails the match if, immediately to the left of the current location, there are any zero or more backslashes from the start of string
  • \\+ - one or more backslashes.
Related