regex question

C

CSharper

I have the following code and the first expression get replaced
properly but the second one does not replace at all. Only difference
in the two, the later one has escape sequences inside the string.

static void Main(string[] args)
{
string key = "Tables";
string original = "select lot of tables";
string val = "yalks";
Regex myRegEx = new Regex(key,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
string sRetStr = myRegEx.Replace(original, val);
key = @"name\age\sex";
original = @"select lot of tables with name\age\sex";
val = "columns";
myRegEx = new Regex(key,
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant| RegexOptions.IgnorePatternWhitespace);
sRetStr = myRegEx.Replace(original, val);
}

What could be the problem?

Thanks,
 
C

CSharper

I have the following code and the first expression get replaced
properly but the second one does not replace at all. Only difference
in the two, the later one has escape sequences inside the string.
[...]
What could be the problem?

You don't need to escape the backslash for the C# compiler, but you still 
need to do it for the Regex class.

Pete

I am sorry I lost you. The source is coming from a data file (for
simplicity, I just put the hard coded value. Same goes for the key, it
is also coming from a data file). I lost you in the compiler portion.
 
C

CSharper

The code you posted used the "@" symbol so that you don't have to escape  
the backslash.  That's all I meant.

No matter where you get the text from, you need to escape special Regex  
characters, such as the backslash.  Try using the Regex.Escape() methodon  
your key string before passing it to the Regex class.

Pete

Thank you very much and the escape does the trick for me. I was
escaping both the source and key first. Iike you said, escape is only
needed for key.
Thanks again.
 

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