Eric
Eric

Reputation: 3241

Regular expression to put a backslash at the end of a path, if necessary

Why doesn't this approach work?

Regex.Replace(Regex.Replace("c:\\test", "$", "\\"), "\\\\$", "\\")   //expected results
Regex.Replace(Regex.Replace("c:\\test\\", "$", "\\"), "\\\\$", "\\") //not expected results

I would think that it would put in a backslash at the end of the line and then take out a double backslash out, if it's there. The "$", "\" part of the regex seems to work, but not the "\\$", "\" part.

-Eric

Upvotes: 0

Views: 302

Answers (2)

lai
lai

Reputation: 1171

I suppose that you'll want that to concatenate at some point some file name or subdirectory name.

In that case, why bother with the slash?

Check out Path.Combine()

Upvotes: 0

JaredPar
JaredPar

Reputation: 755587

Using a Regex for this task is overkill. A Regex is best for matching patterns and in this case you are just matching a single character. Yes this is a pattern but for simple actions like this using a direct character comparison is much more efficient

string EnsureBackSlash(string path) { 
  if (String.IsNullOrEmpty(path) || path[path.Length - 1] != '\\') { 
    return path + "\";
  }

  return path;
}

Upvotes: 1

Related Questions