我正在尝试替换给定字符串中出现的所有名称。我正在使用正则表达式,因为简单的子字符串匹配在这种情况下不起作用,我需要匹配完整的单词。
我的问题是我只能匹配空格前后的单词。但例如,当字符串后跟空格时,我无法替换它,例如:
toReplace()
与: theReplacement()
我的正则表达式替换方法如下所示:
void replaceWord(std::string &str, const std::string& search, const std::string& replace)
{
// Regular expression to match words beginning with 'search'
// std::regex e ("(\\b("+search+"))([^,. ]*)");
// std::regex e ("(\\b("+search+"))\\b)");
std::regex e("(\\b("+search+"))([^,.()<>{} ]*)");
str = std::regex_replace(str,e,replace) ;
}
正则表达式应该是什么样子才能忽略前导和尾随的非字母数字?
最佳答案
你需要
- 使用 std::regex_replace(search, std::regex(R"([.^$|{}()[\]*+?/\\]) 转义正则表达式模式中的所有特殊字符"), std::string(R"(\$&)"))
- 使用
std::regex_replace(replace, std::regex("[$]"), std::string("$$$$")) 转义替换模式中的所有特殊字符
(也就是说,如果您替换为文字$1
文本,则$
可以设置为$$
,因此要替换为双>$
,我们需要$$$$
来替换这里) - 用明确的单词边界包裹您的搜索模式,即
"(\\W|^)("+search+")(?!\\w)
< - 替换时,在替换模式的开头添加
$1
以保留空格(如果它与(\W|^)< 匹配并捕获到第一组中)/code> 模式)。
参见C++ sample code :
std::string replaceWord(std::string &str, std::string& search, std::string& replace)
{
// Escape the literal regex pattern
search = std::regex_replace(search, std::regex(R"([.^$|{}()[\]*+?/\\])"), std::string(R"(\$&)"));
// Escape the literal replacement pattern
replace = std::regex_replace(replace, std::regex("[$]"), std::string("$$$$"));
std::regex e("(\\W|^)("+search+")(?!\\w)");
return std::regex_replace(str, e, std::string("$1") + replace);
}
那么,
std::string text("String toReplace()");
std::string s("toReplace()");
std::string r("theReplacement()");
std::cout << replaceWord(text, s, r);
// => String theReplacement()
关于c++ - 正则表达式替换方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63637904/