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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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++"), "<b>${0}</b>", RegexOptions.IgnoreCase); And it works fine. Thank you all.
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);

3 Comments

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?
You can check this for other special characters: stackoverflow.com/questions/399078/… . Among them are the following: (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space)
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++"), "<b>${0}</b>", RegexOptions.IgnoreCase); And it works fine. Thank you all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.