C++ 如何使这个正则表达式替换函数有效?

C++ 如何使这个正则表达式替换函数有效?,c++,c++11,C++,C++11,我正在使用此函数对std::string执行正则表达式替换: String regexReplace(String s,String search,String replace,String modifier,int user){ bool case_sensitive=true,global=false; String replaced_string=s; if(modifier=="gi" || modifier=="ig"){global=true;case_sen

我正在使用此函数对
std::string
执行正则表达式替换:

String regexReplace(String s,String search,String replace,String modifier,int user){
    bool case_sensitive=true,global=false;
    String replaced_string=s;
    if(modifier=="gi" || modifier=="ig"){global=true;case_sensitive=false;}
    else if(modifier=="i"){case_sensitive=false;}
    else if(modifier=="g"){global=true;}

    try {
        std::regex re (search);
        if(user==1){re=createRegex(search,case_sensitive);}
        else if(!case_sensitive){re= Regex (search, REGEX_DEFAULT | ICASE);}

        if(global){
        replaced_string=std::regex_replace (s,re,replace,std::regex_constants::format_default);
        }
        else{
        replaced_string=std::regex_replace (s,re,replace,NON_RECURSIVE_REGEX_REPLACE);
        }
    } 
    catch (std::regex_error& e) {
      printErrorLog("Invalid replace string regex: "+search);
      Exit(1);
    }
    return replaced_string;
}
typedef
s和
#定义使用的
s:

typedef std::regex Regex;
typedef std::string String;

#define REGEX_DEFAULT std::regex::ECMAScript
#define ICASE std::regex::icase
#define NON_RECURSIVE_REGEX_REPLACE std::regex_constants::format_first_only
但此函数在14x4次连续执行时消耗约0.3秒:

res=regexReplace(res,"([^\\.]*\\.\\d+?)0+$","$1","i",0);
res=regexReplace(res,"([^\\.]*\\.\\d+?)0+(e.*)$","$1$2","i",0);
res=regexReplace(res,"([^\\.]*)\\.0*$","$1","i",0);
res=regexReplace(res,"([^\\.]*)\\.0*(e.*)$","$1$2","i",0);
我可以让它更有效地减少执行时间吗

注:


createRegex()
函数没有被调用(
user=0
默认值)。

我想答案取决于平台(编译器、操作系统、c++运行时),它取决于很多参数,主要包括您的开发技能,但是一种方法可能是使用手工制作的解析器而不是正则表达式,因为正则表达式由通用引擎提供动力,而您确实知道您的案例的具体需求,因此可以更好地进行优化。