Unrecognized escape sequence

  • Thread starter Christopher Ireland
  • Start date
C

Christopher Ireland

Hi --

Any ideas on this one please ...

The following code works as expected:
private void Form1_Load(object sender, System.EventArgs e) {
string text = "The quick brown"+ " FOX " +"jumps over the lazy dog.";
string pattern = "FOX";
string replacement = "cat";

string
result=Regex.Replace(text,pattern,replacement,System.Text.RegularExpressions
..RegexOptions.IgnoreCase);
richTextBox1.Text = result;
}

However, this code doesn't:
private void Form1_Load(object sender, System.EventArgs e) {
string text = "The quick brown"+ " C:\\TEST\\MyDirectory " +"jumps over the
lazy dog.";
string pattern = "C:\\TEST\\MyDirectory";
string replacement = "..\\..";

string
result=Regex.Replace(text,pattern,replacement,System.Text.RegularExpressions
..RegexOptions.IgnoreCase);
richTextBox1.Text = result;
}

The above bombs out with an Unrecognized escape sequence. All I'm trying to
do is perform a case-insensitive replace function on text with directory
paths in it ..

Many thanks!

Chris.
 
N

Niki Estner

The problem is that regular expressions use the backslash as escape
characters, too; Use Regex.Escape(pattern).
This will escape all regex-metacharacters in the pattern string.

Niki
 
C

Christopher Ireland

Niki Estner said:
The problem is that regular expressions use the backslash as escape
characters, too; Use Regex.Escape(pattern).
This will escape all regex-metacharacters in the pattern string.

Excellent! Thanks Niki!!

Chris.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top