我正在做一个项目,我需要找到以 $< 开头并以 >$ 结尾的单词,并将其替换为存储在变量中的单词。
例子
string a ="hello";
string b = "Fellow $<world>$, full of $<smart>$ people"
std::cout<<std::regex_replace(b, "\\b($<)([^ ]*)(>$)\\b", a); //should print "Fellow hello, full of hello people"
但似乎这是不可能直接实现的。
我该如何解决这个问题?
最佳答案
除了两点,你的代码没有问题:
- 正则表达式 - 你没有转义
$
这意味着字符串结束,\b
$
前后的单词边界这需要一个单词字符出现在$
旁边符号。 regex_replace
没有签名就像你用的那个。
所以,正确的正则表达式是
\$<[^<>]*>\$
\$
匹配文字 $
, 然后是文字 <
, 然后是 <
以外的 0 个或多个字符和 >
直至文字 >$
.
在 C++ 中,您可以使用原始字符串 ( R"()"
) 来声明正则表达式对象,它将减轻两次转义元字符的痛苦。
参见 IDEONE demo :
string a ="hello";
string b = "Fellow $<world>$, full of $<smart>$ people";
std::cout<<std::regex_replace(b, std::regex(R"(\$<[^<>]*>\$)"), a);
输出:Fellow hello, full of hello people
关于c++ - 如何在 cpp 中使用 std::regex_replace() 函数查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33384365/