我试图在 C++ 的字符串中找到所有"#"字符并用 "hash" 替换它们,但正则表达式无法识别字符"#"

I'm trying to find all the "#" characters in a string in C++ and replace them with "hash" but the regex does not recognise the character "#"

本文关键字:字符 替换 hash 识别 正则表达式 字符串 C++      更新时间:2023-10-16

我试图在C++中找到字符串中的所有"#"字符,并用"hash"替换它们,但正则表达式无法识别字符"#""#""\#"。你知道我必须用什么才能找到#吗?

std::string local = std::regex_replace(test, "#", "hash");

正如Robert Harvey所建议的那样,使用std::sting::replace效果良好。它希望用一个索引来替换through,而不是字符。因此,您必须将它与诸如"std::string::find like So:"之类的东西结合使用

int index;
while( (index = str.find("#') != std::string::npos) {
    str.replace(index, 1, "hash");
}

您可以对更复杂的字符串使用相同的想法来匹配,所以如果您不需要模式替换,这将起作用。

此处运行示例:http://ideone.com/WqDZAl