Reputation: 703
string pattern = ".+\\";
foreach (string file in files){
richTextBox2.Text += Regex.Replace(file, @pattern, String.Empty) +"\n";
}
I am trying to do what should be a simple pattern match and replace, file consists of full path, for example: d:\test\t.txt
. But everytime it crushes and says Illegal \ at the end of the pattern.
No joy where am I going wrong?
Upvotes: 1
Views: 107
Reputation: 5636
One more solution You may use @
before strings to avoid having to escape special characters like
string pattern = @".+\\";
Upvotes: 3
Reputation: 336128
You need to escape the backslash twice:
string pattern = ".+\\\\";
First, you need to escape it at the string processing level, so "\\"
becomes \
to the regex engine.
Second, the regex engine also uses backslashes for special escape sequences, so if you want to match a literal backslash with a regex, you need to use \\
.
Since backslashes are rather common in regexes, it's usually a good idea to use verbatim strings for them (see Rahul's solution).
Upvotes: 4