3

我要努力让它发挥作用。到目前为止,这是我所拥有的,但 ç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);

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

更新 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);
4

2 回答 2

3

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

要匹配的模式

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

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

输出格式

同样,双引号在匹配替换格式(或任何正确的术语)中并不神奇,但反斜杠是。因此,要在输出中获得两个反斜杠,字符串中需要四个,这意味着字符串文字中需要 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而不是Wor来检查n。或者你可以不打扰,如果你碰巧对此不好奇。)

试一试,然后报告...

于 2012-07-12T22:21:02.190 回答
1

我在这里没有任何提升,但单(反)斜杠必须在正则表达式中写为 \\ ,因此 C++ 字符串文字是四个反斜杠。替换字符串必须转义并再次在 c++ 中,所以它的八个反斜杠。

正则表达式中的双引号不能被转义,所以它是“”,而在 c++ 中是\“\”。替换必须再次被转义,所以它的 \\",当然在 c++ 中,所以它是 \\\\"。

根据您的更新 3,模式和替换字符串必须像这样初始化:

const std::string singleslashpat("\\\\");
const std::string doublequotepat("\"\"");
const std::string doubleslash("\\\\\\\\");
const std::string slashquote("\\\\\"");
于 2012-07-12T22:23:54.067 回答