Saskia Saskia - 2 months ago 16
C# Question

Regular expressions under Microsoft... (C#)

I want to know a very simple thing: does a string end with a backslash yes or no?

string bla = @"C:\";
if ( ! Regex.IsMatch(bla, "\b$")) { bla = bla + @"\"; }


But it's not working. I want to add a slash if there's no slash at the end of the string. I tried several ways, even if I just try to match a backslash, without having it to be at the end of the string, its a huge problem:

Regex.IsMatch(bla, "\b") // Not working
Regex.IsMatch(bla, @"\") // Giving me and exception even!
Regex.IsMatch(bla, @"\\$") // not working


I'm out of options. How the .... can I match a backslash with C#?

Answer

I want to know a very simple thing: does a string end with a backslash yes or no.

Then you don't need regex...

string str = "your string here";
str.EndsWith(@"\"); // true or false

If you really want to do it the regex way though, you just have to make sure your regex is correct. This should work:

.*\\$

.* will match any optional leading characters
\\ will match the '\' and has been escaped with another '\'
$ will match until the end of your string.