#include

时间:2023-03-09 02:24:36
#include <boost/regex.hpp>

boost C++的正则表达式库boost.regex可以应用正则表达式于C++。正则表达式大大减轻了搜索特定模式字符串的负担,在很多语言中都是强大的功能。

boost.regex库中两个最重要的类是boost::regex和boost::smatch,它们都在boost/regex.hpp文件中定义。前者用于定义一个正则表达式,而后者可以保存搜索结果。

小结:C++的正则表达式库早已有之,但始终没有哪个库纳入到标准化流程中。目前该库已经顺利的成立新一代C++标准库中的一员,结束了C++没有标准正则表达式支持的时代。

1 boost::regex_match

正则表达式匹配

2 boost::regex_replace

正则表达式替换

3 boost::regex_search

正则表达式检索

 #include <iostream>
#include <boost/regex.hpp> void main()
{
std::string str = "chinaen 8Glish"; boost::regex expr("(\\w+)\\s(\\w+)"); //+ 用来表示重复一或多次
//d-digit 任何0-9之间的数字
//s-space 任何空格字符
//u-upper A-Z之间的大写字母。如果设置了地域的话,可能包含其他字符
//w-word 任何单词字符-字母数字下划线 std::cout << boost::regex_match(str, expr) << std::endl;//匹配1,不匹配0 boost::smatch what; if (boost::regex_search(str, what, expr))//正则表达式检索
{
std::cout << what[] << std::endl;
std::cout << what[] << std::endl;
std::cout << what[] << std::endl;
std::cout << what[] << std::endl;
}
else
{
std::cout << "检索失败" << std::endl;
}
}

boost::regex_replace

正则表达式替换

//s-space 任何空格字符

 #include <iostream>
#include <boost/regex.hpp> void main()
{
std::string str = "chinaen 8Glish"; boost::regex expr("\\s");//s-space 任何空格字符 std::string tihuan = "____"; std::cout << boost::regex_replace(str, expr, tihuan) << std::endl;//把expr替换
}