如何分辨C++;将正则表达式视为纯文本/转义所有字符 < >我正在编写一个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; }
它将如何分辨C++;将正则表达式视为纯文本/转义所有字符 < >我正在编写一个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; },c++,regex,std,C++,Regex,Std,它将str中出现的所有strOld替换为strNew。我试图使用std::regex和std::regex\u replace来实现它。如果useRegex是真的,那么它工作得很好。但是,如果useRegex为false,我无法告诉他们strOld只是一个普通字符串而不是正则表达式字符串 例如,当我打电话时: string output=Replace("hello.",".","?",false,true); 它返回“???”,而我希望它是“hello?”一半的解决方案是预处理正则表达式并手
str
中出现的所有strOld
替换为strNew
。我试图使用std::regex
和std::regex\u replace
来实现它。如果useRegex
是真的,那么它工作得很好。但是,如果useRegex
为false
,我无法告诉他们strOld
只是一个普通字符串而不是正则表达式字符串
例如,当我打电话时:
string output=Replace("hello.",".","?",false,true);
它返回
“???”
,而我希望它是“hello?”
一半的解决方案是预处理正则表达式并手动转义所有元字符。如果C++11中缺少此功能,这是最好的解决方案,从评论中可以看出这一点。不清楚问题出在哪里。相关代码是什么?它以什么方式不起作用?我猜你也不想要const string&str
,或者你将无法对其进行任何更改…为什么不在这种情况下避免使用正则表达式,而在useRegex=false
的情况下只使用普通的std::string
功能(find
/replace
),如果我在功能上使用std::string
(find
/replace
),则实现不区分大小写的替换有点困难。如果/其他
,则至少额外增加一个。如果有什么东西可以告诉std::regex_replace
输入只是一个普通字符串而不是regex,那就太完美了。我认为这是C++11中缺少的一个特性。在Java中,有一个函数可以使使用regex的函数中的任意字符串被识别为文字字符串。听起来很有趣!我将尝试这个解决方案。