-2

I am trying to do a find replace in a string of text. I am using Regex like this:

Regex regexText = new Regex("Test.Value");

strText = regexText.Replace(strText, value);

In this example I am trying to find the string "Test.Value" in a text string. However if this value appears in the string the replace does not happen.

If I remove the dots eg:

Regex regexText = new Regex("TEST");

strText = regexText.Replace(strText, value);

If I put the word "TEST" in the string, it replaces it just fine.

Is there a way to get this to work with strings with "."'s in?

Dean
  • 360
  • 1
  • 10
  • 27

1 Answers1

0

You have to escape the dot:

Regex regexText = new Regex(@"Test\.Value");

As you wrote it, the regex is just looking for "Test", followed by any character except a line feed, followed by "Value".

On the top of that, if the text you are looking for is a little bit different, a case insensitive matching could help you out:

Regex regexText = new Regex(@"Test\.Value", RegexOptions.IgnoreCase);

Anyway, in this case I don't think a Regex is necessary. A simple string replace should do the job:

strText.Replace("Test.Value", value);
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • If a `.` did not match the dot why do you think your even more restricted pattern (as `\.` only matches `.` char) will help? – Wiktor Stribiżew Nov 16 '17 at 21:35
  • 1
    It doesn't help but it's the way the regex in the OP should work. If he is attempting to replace "Test.Value" and his string contains "Test5Value", that will be stripped off too. Also, the @ could be a fix. If the regex doesn't hold, I also proposed an alternative. – Tommaso Belluzzo Nov 16 '17 at 21:37
  • 1
    `@` has nothing to do with OP's pattern. Also, if the problem is with escaping a `.`, the question is an evident dupe of [What special characters must be escaped in regular expressions?](https://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions). Why answer it? – Wiktor Stribiżew Nov 16 '17 at 21:39