在任何情况下(查找gcc的phrase regex on this page)C++(0x,11,tr1)正则表达式do not really work (stackoverflow),所以最好在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
switch)中轻松完成。
因此,你需要两遍,因为你已经怀疑:
...
string test = "test replacing \"these characters\"";
test = regex_replace(test, regex("\\s+"), "_");
test = regex_replace(test, regex("\\W+"), "");
...
编辑2:
如果有可能在regex_replace
使用回调函数tr()
,那么你可以修改那里的替代,如:
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++ 或任何数量随之而来的工作。
问候
RBO
你为什么在你的例子输出挂断最后'“'-char – 2012-07-16 17:20:49
@rubberboots - 因为只有白色的空间应该用下划线,任何其他非字母和数字来代替字符应该被替换为没有任何内容 – pstrjds 2012-07-16 17:24:51
我看到了,所以你希望在一次传递中有不同的替换文本,这在C++ regex中不起作用,如果有人发现这个问题,我想用这个太;-) – 2012-07-16 17:52:38