c++ 11 正则表达式
常用的方法 regex_match regex_search regex_replace 等.
regex_match 要求正则表达式必须与模式串完全匹配,例如:
string str = "o ";
regex pattern("o\\s");
bool matched = regex_match(str,pattern);
if (matched) {
cout << "matched.." << endl;
}else{
cout << "not matched." << endl;
}
上面就可以匹配.如果修改一下下:
string str = "o 1";
regex pattern("o\\s");
bool matched = regex_match(str,pattern);
if (matched) {
cout << "matched.." << endl;
}else{
cout << "not matched." << endl;
}
就是 not matched. 了
regex_match 包含子模式的匹配,并且显示匹配结果,主要使用了
match_results<string::const_iterator> result
存储匹配后的结果.
string str = "1:2:33:344";
regex pattern("(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})");
match_results<string::const_iterator> result;
bool matched = regex_match(str,result,pattern);
if (matched) {
cout << "matched.." << endl;
printf("result.size = %d\n",(int)result.size());
for (int i = 0; i < result.size(); ++i) {
printf("result[%d]:%s\n",i,result[i].str().c_str());
}
}else{
cout << "not matched." << endl;
}
输出:
matched..
result.size = 5
result[0]:1:2:33:344
result[1]:1
result[2]:2
result[3]:33
result[4]:344
主意打印的结果result[0]
regex_search 只要求存在匹配项就可以.
string str = "o 1";
regex pattern("\\w\\s");
bool matched = regex_search(str,pattern);
if (matched) {
cout << "matched.." << endl;
}else{
cout << "not matched." << endl;
}
输出: matched..
如果只想输出第一个匹配项,使用 smatch 存储结果
string str = "o 1s;23235;t;dsf;sd 66 ";
regex pattern(";");
smatch result;
bool matched = regex_search(str,result,pattern);
if (matched) {
cout << "matched.." << endl;
cout << "result.size:" << result.size() << endl;
for (int i = 0; i < result.size(); ++i) {
printf("result[%d]:\t%s\n",i,result[i].str().c_str());
}
}else{
cout << "not matched." << endl;
}
输出结果为:
matched..
result.size:1
result[0]: ;
如果想输出所有的匹配结果,则需要使用 sregex_token_iterator
string str = "o 1s 23235 t ds f sd 66 ";
regex pattern("\\w\\s");
sregex_token_iterator end;
sregex_token_iterator start(str.begin(),str.end(),pattern);
while (start != end) {
cout << (*start) << endl;
++start;
}
输出为:
o
s
5
t
s
f
d
6
regex_replace 方法替换掉匹配上的
string str = "o 1s 23235 t ds f sd 66 ";
regex pattern("\\w\\s");
bool matched = regex_search(str,pattern);
if (matched) {
cout << "matched ." << endl;
auto newStr = regex_replace(str,pattern,"---");
printf("newStr : %s\n",newStr.c_str());
}else{
cout << "not matched ." << endl;
}
输出结果为:
matched .
newStr : ---1---2323------d------s---6---
上面就是c++11 正则表达式的基本使用.
内容基本来自于: 这个作者