chosenOne Thabs
chosenOne Thabs

Reputation: 1640

Regex Nested quantifier +

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.

Upvotes: 0

Views: 4162

Answers (2)

ionden
ionden

Reputation: 12776

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

Upvotes: 2

SLaks
SLaks

Reputation: 887195

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

Upvotes: 4

Related Questions