Disciples
Disciples

Reputation: 703

Regex.Replace's pattern doesn't work correctly

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

Answers (2)

Rahul
Rahul

Reputation: 5636

One more solution You may use @ before strings to avoid having to escape special characters like

string pattern = @".+\\";

CHECK MSDN

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

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

Related Questions