一、前言
正则表达式是一种比较常见的提取字符串的思路,主流的语言都是有这个玩意的,那么C++中如何使用正则呢?
二、代码
1.简单示例
#include <iostream>
#include <regex>
using namespace std;
int main(){
string str = "asadasd";
regex e(".*");
smatch m;
if (regex_search(str, m, e)){
cout << m[0] << endl;
}
getchar();
return 0;
}
测试结果如图:
2.匹配花括号1
这个只能匹配一个{},出现多个{},得不到我想要的结果。
#include <iostream>
#include <regex>
using namespace std;
int main(){
string str = "asdas{assfasiofasf},asds";
regex e("\\{(.*)\\}");
smatch m;
if (regex_search(str, m, e)){
cout << m[0] << endl;
cout << m[1] << endl;
}
getchar();
return 0;
}
测试结果如图
3.匹配花括号2
使用迭代器
#include <iostream>
#include <string>
#include <regex>
#include <vector>
using namespace std;
vector<string> GetRegex(string s, string pattern){
auto res = vector<string>();
regex r(pattern);
sregex_iterator pos(s.cbegin(), s.cend(), r), end;
for (; pos != end; ++pos)
res.push_back(pos->str(0));
return res;
}
int main() {
string input = "{sdasdas},{asfasasdas},asdsa{safsadass}";
string pattern = "\\{(.+?)\\}";
for (auto s : GetRegex(input, pattern))
cout << s << ", ";
getchar();
}
测试结果如图:
三、最后
晚安。