boost 库 regex 简单使用
1. 验证输入
#include <iostream>
#include <cassert>
#include <string>
#include "boost/regex.hpp"
int main()
{
// 3 digits, a word, any character, 2 digits or "N/A", // a space, then the first word again
boost::regex reg("\\d{3}([a-zA-Z]+).(\\d{2}|N/A)\\s\\1");
std::string correct="123Hello N/A Hello";
std::string incorrect="123Hello 12 hello";
assert(boost::regex_match(correct,reg)==true); //结果 1
assert(boost::regex_match(incorrect,reg)==false); //结果 1
}2.查找
int main()
{
boost::regex reg("(.*?)(\\d{12}).(\\d{12}).(\\d{1})");
boost::cmatch m;
const char* text = "c:\\fdasfda\\afasdfasfa\\201402261025_201402261025_1.csv"; //例子是文件路径 201402261025是日期
if(boost::regex_search(text,m, reg))
{
if (m[1].matched)
std::cout << "(.*) matched: " << m[1].str() << '\n'; //c:\\fdasfda\\afasdfasfa\\
if (m[2].matched)
std::cout << "Data1: " << m[2] << '\n'; //201402261025
if (m[3].matched)
std::cout << "Data2: " << m[3] << '\n'; //201402261025
if (m[4].matched)
std::cout << "Device: " << m[4] << '\n'; //1
}
return 0;
}
int main()
{
boost::regex reg("(Colo)(u)(r)", boost::regex::icase|boost::regex::perl);
std::string s = "Colour, colours, color, colourize";
s = boost::regex_replace(s,reg,"$1$3");
std::cout << s; ///Color, colous, color, colorize
}
4.用 regex_token_iterator 分割字符串
int main()
{
boost::regex regg( "/" );
vector<string> vector_string;
string stringinfo = "zz/dd/pp/ee/ff/mm";
boost::sregex_token_iterator it( stringinfo.begin(), stringinfo.end(), regg, -1);
boost::sregex_token_iterator end;
while( it != end )
{
vector_string.push_back(*it++);
}
cout<< vector_string.size() <<endl; //6
cout<< std::count(stringinfo.begin() ,stringinfo.end() ,'/')+1 <<endl; //6
cout<< vector_string[0]<<endl; //zz
getchar();
return 0;
}

本文通过四个实例展示了Boost库regex的高级使用方法:验证输入、查找特定模式、替换字符串内容以及使用regex_token_iterator分割字符串。每个实例都包含代码实现和详细说明,帮助读者深入理解regex的强大功能。

1415

被折叠的 条评论
为什么被折叠?



