1
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?

0

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Bingo! When doing a regex it's best to use a verbatim string to reduce confusion. @".+\\"
3

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

string pattern = @".+\\";

CHECK MSDN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.