使用boost::regex_search进行字符串提取
使用正则表达式来能够处理很复杂的字符串,这里只分析以下如何使用boost::regex_search进行字符串提取。
主角登场:
// boost::regex_search
1 template <class BidirectionalIterator, class Allocator, class charT, class traits>
2 bool regex_search(BidirectionalIterator first, BidirectionalIterator last,
3 match_results<BidirectionalIterator, Allocator>& m,
4 const basic_regex<charT, traits>& e,
5 match_flag_type flags = match_default);函数概要
判断在[first,last)内是否存在某个子序列匹配正则表达式e, 参数flags用来控制表达式如何匹配字符序列。 如果存在这样的序列则返回true,否则返回false。参数介绍
重载的函数很类似,这里我们只分析这份
- first,last是指向我们要处理的串的首尾迭代器
- m是匹配结果,是我们下面说的重点
- e是正则表达式
- flags是匹配规则
match_results结构的主要成员/方法:
bool empty() const : match_result是否为空,正常应为0(regex_search返回真时),regex_search返回假时match_results结构不确定
size_t size() const : 返回正则表达式中的元组数+1,元组即正则表达式的中的()
const_reference operator[](int n) const : 返回一个sub_match引用,当n=0时返回[first,last)的匹配结果,当0<n<=size时,返回对应元组的匹配结果,
当n>size时返回一个matched值为假的sub_match结构,元组按照左边括号的顺序和sub_match相对应,从1开始。
如regex:(([a-z]+).([0-9]+))+ m[1]:(([a-z]+).([0-9]+)) m[2]:([a-z]+) m[3]:([0-9]+)
sub_match结构的主要成员/方法:
bool matched: 是否匹配
什么是sub_match:
typedef sub_match<const char*> csub_match;
typedef sub_match<const wchar_t*> wcsub_match;
typedef sub_match<std::string::const_iterator> ssub_match;
typedef sub_match<std::wstring::const_iterator> wssub_match;例子
#include <string>
#include <iostream>
#include <boost\regex.hpp>
void main()
{
std::string str = "192.168.1.1";
boost::regex expression("([0-9]+).([0-9]+).([0-9]+)");
boost::smatch what;
if ( boost::regex_search(str, what, expression) )
{
std::cout << what.size() << std::endl;
for (size_t i = 0; i < what.size(); ++i)
{
if (what[i].matched)
std::cout << what[i] << std::endl;
}
}
}// Output:// 4// 192.168.1// 192// 168// 1参考资料
转载请注明出处:
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步