我正在尝试用不同的替换模式替换字符串中的某些模式。
例子:
string test = "test replacing \"these characters\"";
我想要做的是将所有“”替换为“_”,并将所有其他非字母或数字字符替换为空字符串。我创建了以下正则表达式,它似乎正确标记化了,但我不确定如何(如果可能)使用 regex_replace
执行条件替换。
string test = "test replacing \"these characters\"";
regex reg("(\\s+)|(\\W+)");
替换后的预期结果是:
string result = "test_replacing_these_characters";
编辑: 我不能使用 boost,这就是为什么我将它从标签中删除的原因。所以请不要回答包含提升的问题。我必须用标准库来做这件事。可能是不同的正则表达式可以实现目标,或者我只是被困在做两次传递。
编辑2:
我不记得在我原来的正则表达式时 \w
中包含哪些字符,在查找之后我进一步简化了表达式。同样,目标是任何匹配\s+ 的内容都应替换为“_”,任何匹配\W+ 的内容都应替换为空字符串。
最佳答案
C++ (0x, 11, tr1) 正则表达式 do not really work (stackoverflow)在每种情况下(查找 gcc 的 phrase regex on this page),所以最好是 use boost一阵子。
如果您的编译器支持所需的正则表达式,您可以尝试:
#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main(int argc, char * argv[]) {
string test = "test replacing \"these characters\"";
regex reg("[^\\w]+");
test = regex_replace(test, reg, "_");
cout << test << endl;
}
以上内容适用于 Visual Studio 2012Rc。
编辑 1:要一次性替换为两个不同的字符串(取决于匹配),我认为这在这里行不通。在 Perl 中,这可以在评估的替换表达式( /e
开关)中轻松完成。
因此,正如您已经怀疑的那样,您需要两次通过:
...
string test = "test replacing \"these characters\"";
test = regex_replace(test, regex("\\s+"), "_");
test = regex_replace(test, regex("\\W+"), "");
...
编辑 2:
如果可以使用回调函数 tr()
在 regex_replace
, 然后你可以在那里修改替换,比如:
string output = regex_replace(test, regex("\\s+|\\W+"), tr);
与 tr()
做替换工作:
string tr(const smatch &m) { return m[0].str()[0] == ' ' ? "_" : ""; }
问题就解决了。不幸的是,在某些 C++11 正则表达式实现中没有这样的重载,但是 Boost has one 强>。以下将与提升一起使用并使用一次通过:
...
#include <boost/regex.hpp>
using namespace boost;
...
string tr(const smatch &m) { return m[0].str()[0] == ' ' ? "_" : ""; }
...
string test = "test replacing \"these characters\"";
test = regex_replace(test, regex("\\s+|\\W+"), tr); // <= works in Boost
...
也许有一天这将适用于 C++11 或接下来出现的任何数字。
问候
rbo
关于c++ - 有条件地替换字符串中的正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/747735/