简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM