gpt4 book ai didi

regex - 使用 boost::regex 将反斜杠替换为双反斜杠并将双引号替换为斜杠引号

转载 作者:行者123 更新时间:2023-12-01 09:07:23 25 4
gpt4 key购买 nike

我正竭尽全力让它发挥作用。这是我目前所拥有的,但是 ça ne marche pas。

const std::string singleslash("\\\\\\\\");
const std::string doublequote("\\\"\"\\");
const std::string doubleslash("\\\\\\\\\\\\");
const std::string slashquote("\\\\\\\\\"\\");

std::string temp(Variables);
temp.assign(boost::regex_replace(temp,boost::regex(singleslash),doubleslash,boost::match_default));
temp.assign(boost::regex_replace(temp,boost::regex(doublequote),slashquote,boost::match_default));

有人救救我吧。

更新 看来我没有正确使用 regex_replace。这是一个更简单的例子,它也不起作用......

std::string w("Watermelon");
temp.assign(boost::regex_replace(w,boost::regex("W"),"x",boost::match_all | boost::format_all));
MessageBox((HWND)Window, temp.c_str(), "temp", MB_OK);

这给了我“西瓜”而不是“西瓜”

更新 2 使用 boost::regex 错误......这个有效

boost::regex pattern("W");
temp.assign(boost::regex_replace(w,pattern,std::string("x")));

更新 3 这是最终起作用的

std::string w("Watermelon wishes backslash \\ and another backslash \\ and \"\"fatness\"\"");
temp.assign(w);

MessageBox((HWND)Window, temp.c_str(), "original", MB_OK);

const boost::regex singlebackslashpat("\\\\");
const std::string doublebackslash("\\\\\\\\");
temp.assign(boost::regex_replace(w,singlebackslashpat,doublebackslash));
MessageBox((HWND)Window, temp.c_str(), "double-backslash", MB_OK);

const boost::regex doublequotepat("\"\"");
const std::string backslashquote("\\\\\\\"");
temp.assign(boost::regex_replace(temp,doublequotepat,backslashquote));
MessageBox((HWND)Window, temp.c_str(), "temp", MB_OK);

最佳答案

所以,我不是 boost::regex 专家,也没有在我现在的地方方便地安装 Boost,但让我们尝试逐步解决这个问题。

要匹配的模式

要匹配输入中的双引号,您只需要在正则表达式中使用双引号(双引号在正则表达式中并不神奇),这意味着您只需要一个包含双引号的字符串。 "\"" 应该没问题。

要匹配输入中的反斜杠,您需要在正则表达式中转义反斜杠,这意味着两个连续的反斜杠;每一个都需要在字符串文字中再次加倍。所以“\\\\”。 [已编辑:我之前输入了 8 而不是 4,这是一个错误。]

输出格式

同样,双引号在匹配替换格式(或任何正确的术语)中并不神奇,但反斜杠是。因此,要在输出中获得两个反斜杠,字符串中需要四个反斜杠,这意味着字符串文字中需要 8 个。所以:"\\\\\\\\"

要获得一个反斜杠后跟一个双引号,您的字符串需要是两个反斜杠和一个双引号,并且所有这些都需要在字符串文字中以反斜杠开头。所以:"\\\\\""

[编辑以添加实际代码以便于复制和粘贴:]

const std::string singleslash("\\\\");
const std::string doublequote("\"");
const std::string doubleslash("\\\\\\\\");
const std::string slashquote("\\\\\"");

匹配标志

阅读完 tofutim 的更新后,我尝试查找 match_all,但没有找到它的文档。但是,它确实是一个可能的匹配标志值,并且定义它的头文件旁边有以下神秘注释:“即使设置了 match_any,也必须找到整个输入”。附在 match_any 上的类似含糊的评论是“不在乎我们匹配什么”。我不确定这意味着什么,而且这些标志似乎已被弃用,但无论如何您可能不想使用它们。

(快速查看源代码后,我认为 match_all 所做的是仅当匹配结束于输入末尾时才接受匹配。因此您可以尝试替换 n 而不是 W 在您修改后的测试用例中,看看它是否有效。或者,也许我错过了一些东西,它必须匹配整个输入,您可以通过替换 Watermelon 来检查 而不是 Wn。或者如果您碰巧对此不感兴趣的话,您也不必费心。)

试一试并报告...

关于regex - 使用 boost::regex 将反斜杠替换为双反斜杠并将双引号替换为斜杠引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11461440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com