正则表达式-字符串分割

时间:2022-12-20 18:46:14

C++不像java那样,有自己的字符串分割函数,那么我们在实际应用中如何快速对某些规定格式的字符创进行分割,并提取内容呢?
下面来看代码:
针对IP地址,如何分割:10:22:192:34/17

    //子表达式匹配
regex reg2("(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})/(\\d{1,3})");
vector<string> ip;
ip.push_back("10:22:192:34/17");
ip.push_back("10:122:200:32/34");
ip.push_back("192:121:22:56/36");
vector<smatch>m;
m.resize(ip.size());
for (int i = 0; i < ip.size(); ++i) {
regex_match(ip[i], m[i], reg2);
cout << m[i].str() << endl;
for (int k = 1; k < m[i].size(); ++k)
cout << m[i][k] << " ";
cout << endl;

}

输出结果:

10:22:192:34/17
10 22 192 34 17
10:122:200:32/34
10 122 200 32 34
192:121:22:56/36
192 121 22 56 36

其中,用到了regex_match函数,正则匹配还可以用 sregex_iterator函数,利用迭代器进行正则匹配,上程序:

    for (int i = 0; i < ip.size(); ++i) {
sregex_iterator it(ip[i].begin(),ip[i].end() , reg2);
sregex_iterator it_end;
for (; it != it_end; ++it) {
cout << it->str() << endl;
for (int k = 1; k < it->size(); k++) {
cout << it->str(k) << " ";
}
cout << endl;
}
}

利用正则匹配迭代器更加的方便,不用声明smatch容器,因为迭代器中包含了smatch容器的属性,如下图所示:
正则表达式-字符串分割

完整程序:
好了,给那些偷懒的小伙伴留个完整的程序,拷贝运行:

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
//子表达式匹配
regex reg2("(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})/(\\d{1,3})");
vector<string> ip;
ip.push_back("10:22:192:34/17");
ip.push_back("10:122:200:32/34");
ip.push_back("192:121:22:56/36");
vector<smatch>m;
m.resize(ip.size());
for (int i = 0; i < ip.size(); ++i) {
regex_match(ip[i], m[i], reg2);
cout << m[i].str() << endl;
for (int k = 1; k < m[i].size(); ++k)
cout << m[i][k] << " ";
cout << endl;

}

//迭代器匹配
for (int i = 0; i < ip.size(); ++i) {
sregex_iterator it(ip[i].begin(),ip[i].end() , reg2);
sregex_iterator it_end;
for (; it != it_end; ++it) {
cout << it->str() << endl;
for (int k = 1; k < it->size(); k++) {
cout << it->str(k) << " ";
}
cout << endl;
}
}

system("pause");
return 0;
}

大家如果正则表达不明白,请移步:
C++11标准 正则表达式:http://blog.csdn.net/hutianyou123/article/details/78213301

正则表达式概念:
https://baike.baidu.com/item/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/1700215?fr=aladdin