代码如下:
#include <string>
#include <iostream>
#include <regex>
#define REG "hello(, |)"
int main()
{
std::string s1 = "#hello, hello#";
std::string s2 = std::regex_replace(s1, std::regex(REG), "");
std::cout << s2 << std::endl;
return 1;
}
重点在第5行,这个替换正则表示替换源字符串中的“hello, ”或者“hello”为空,也可以理解为删除源字符串中的“hello, ”或者“hello”子串。
但是实际在windows(vs2017)和linux(gcc 4.9.2)下表现的行为却大不相同。windows编译执行后的输出为“##”,而linux下的输出为“#, #”。
考虑到正则表达式的“懒惰模式”,“贪婪模式”,将第5行改为:
#define REG "hello(, |)*"
则两者行为一致了。
但是,如果将第5行改为:
#define REG "hello(|, )*"
输出又不一样了。改为:
#define REG "hello(|, )"
又一样了。
可能我对正则表达式理解的还不太透彻,先记录下,待以后有空仔细研究研究。