/*
* 正则表达式是在运行时而非编译时编译的
* 构造一个regex或对一个已有的regex赋新值可能非常耗时
* 我们应该尽量避免不必要的regex
*/
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main2()
{
//搜索关键字为ei且前面不是紧接c
string pattern("[^c]ei");
pattern = "[[:alpha:]]*"+pattern+"[[:alpha:]]*";
regex r(pattern);
//smatch 容器类,保存string中搜索的结果
smatch result;
string test_str = "recepit freind theif receive";
// if(regex_search(test_str,result,r)){ //regex_search找到一个就停止了
// cout<<result.str()<<endl;
// }
int i=0;
while (std::regex_search (test_str,result,r)) {
for (auto x:result)
std::cout << i++ << " :" << x << " "<<std::endl;
test_str = result.suffix().str();//当前结果的后续字段
test_str.erase(0,test_str.find_first_not_of(" "));
cout<<test_str<<endl;
}
return 0;
}
int main1 ()
{
std::string s ("there is a needle in this haystack");
std::smatch m;
std::regex e ("needle");
std::cout << "searching for needle in [" << s << "]\n";
std::regex_search ( s, m, e );
if (m.ready()) {
std::cout << m[0] << " found!\n";
std::cout << "prefix: [" << m.prefix() << "]\n";
std::cout << "suffix: [" << m.suffix() << "]\n";
}
return 0;
}
int main(){
std::string s ("there is a needle in this haystack");
//match参数类型与输入序列不匹配,在下面的regex_search使用了一个char*
std::cmatch m;
std::regex e ("needle");
std::cout << "searching for needle in [" << s << "]\n";
std::regex_search ( "there is a needle in this haystack", m, e );
cout<<m[0]<<endl;
return 0;
}
调整main的结构(去掉main后面的数字把其他的加上数字让它只有一个main有效)调出的结果依次是: