0

I'm trying to replace c++ with <b>c++</b> in the following string:

"Select the projects entry and then select VC++ directories. Select show"

I want it to be

"Select the projects entry and then select V<b>C++</b> directories. Select show"

Im using this code :

string cssOld = Regex.Replace(
   "Select the projects entry and then select VC++ directories. Select show",
   "c++", "<b>${0}</b>", RegexOptions.IgnoreCase);

I get the following error :
System.ArgumentException: parsing "c++" - Nested quantifier +.

This code works fine with other text(!c++). It seems like the + operator cause the Regex library to throw an exception.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
chosenOne Thabs
  • 1,480
  • 3
  • 21
  • 39

2 Answers2

4

+ is a special character in regexes; it means "match one or more of the preceding character".

To match a literal + character, you need to escape it by writing \+ (inside an @"" literal)

To match arbitrary literal characters, use Regex.Escape.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Okay thanks a lot. Do i only have to cater for + operator or are there any other operators(*,&,\ etc) that can cause this exception as well? – chosenOne Thabs Mar 18 '12 at 17:02
  • Oh thanks. Regex.Escape did do the job as well. So i changed my code to: string cssOld = Regex.Replace(Regex.Escape("Select the projects entry and then select VC++ directories. Select show "),Regex.Escape("c++"), "${0}", RegexOptions.IgnoreCase); And it works fine. Thank you all. – chosenOne Thabs Mar 18 '12 at 17:14
2

You should escape special characters in regex:

string cssOld = Regex.Replace(
    "Select the projects entry and then select VC++ directories. Select show ",
    @"c\+\+", "${0}", RegexOptions.IgnoreCase);
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
ionden
  • 12,536
  • 1
  • 45
  • 37
  • Okay thanks a lot. Do i only have to cater for + operator or are there any other operators(*,&,\ etc) that can cause this exception as well? – chosenOne Thabs Mar 18 '12 at 17:00
  • You can check this for other special characters: http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions . Among them are the following: (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) – ionden Mar 18 '12 at 17:05
  • Oh thanks. Regex.Escape did do the job as well. So i changed my code to: string cssOld = Regex.Replace(Regex.Escape("Select the projects entry and then select VC++ directories. Select show "),Regex.Escape("c++"), "${0}", RegexOptions.IgnoreCase); And it works fine. Thank you all. – chosenOne Thabs Mar 18 '12 at 17:14