It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我正在编写一个c ++函数来实现字符串替换。函数就像:

using namespace std;

string Replace(const string & str, const string & strOld,
            const string & strNew, bool useRegex, bool caseSensitive)
{
    regex::flag_type flag=regex::basic;
    if(!caseSensitive)
         flag |= regex::icase;

    if(!useRegex)
        // WHAT TO DO ?

    std::regex rx(strOld,flag);
    string output=regex_replace(str,rx,strNew);
    return output;
}


它将strOld中所有出现的str替换为strNew。我试图使用std::regexstd::regex_replace来实现它。如果useRegex为true,它会很好地工作。但是,如果useRegexfalse,我不能告诉他们strOld只是一个普通字符串,而不是正则表达式字符串。

例如,当我打电话时:

string output=Replace("hello.",".","?",false,true);


它返回"??????",而我希望它是"hello?"

最佳答案

中途解决方案是对正则表达式进行预处理,并手动转义所有元字符。如果C ++ 11中缺少此功能(从注释中听起来确实如此),则这是最佳解决方案。

关于c++ - 如何告诉C++正则表达式被视为纯文本/转义所有字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11169767/

10-12 22:02
查看更多