Boost学习系列5-字符串处理-(下)

本文详细介绍了Boost库中的正则表达式库Boost.Regex的使用,包括boost::regex_match(), boost::regex_search()和boost::regex_replace()函数,以及正则表达式与Boost.StringAlgorithms库的结合。此外,还讨论了Boost.Tokenizer库的词汇分割功能和Boost.Format库的格式化输出功能,强调了它们在C++中的应用和优势。" 125480394,7545038,自定义gym环境教程,"['Python', 'gym库', '环境模拟']
摘要由CSDN通过智能技术生成
四、正则表达式库 Boost.Regex

    Boost C++的正则表达式库Boost.Regex可以应用正则表达式于C++。正则表达式大大减轻了搜索特定模式字符串的负担,在很多语言中都是强大的功能。虽然现在C++仍然需要以 Boost C++库的形式提供这一功能,但是在将来正则表达式将进入C++标准库。 Boost Regex库有望包括在下一版的 C++ 标准中。

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

    以下将要介绍 Boost.Regex 库中提供的三个搜索正则表达式的函数。

#include <boost/regex.hpp> 
#include <locale> 
#include <iostream> 

int main() 
{ 
  std::locale::global(std::locale("German")); 
  std::string s = "Boris Schäling"; 
  boost::regex expr("\\w+\\s\\w+"); 
  std::cout << boost::regex_match(s, expr) << std::endl; 
} 

   函数 boost::regex_match() 用于字符串与正则表达式的比较。 在整个字符串匹配正则表达式时其返回值为 true 。

   函数 boost::regex_search() 可用于在字符串中搜索正则表达式。

#include <boost/regex.hpp> 
#include <locale> 
#include <iostream> 

int main() 
{ 
  std::locale::global(std::locale("German")); 
  std::string s = "Boris Schäling"; 
  boost::regex expr("(\\w+)\\s(\\w+)"); 
  boost::smatch what; 
  if (boost::regex_search(s, what, expr)) 
  { 
    std::cout << what[0] << std::endl; 
    std::cout << what[1] << " " << what[2] << std::endl; 
  } 
} 

    函数 boost::regex_search() 可以接受一个类型为 boost::smatch 的引用的参数用于储存结果。 函数 boost::regex_search() 只用于分类的搜索, 本例实际上返回了两个结果, 它们是基于正则表达式的分组。

    存储结果的类 boost::smatch 事实上是持有类型为 boost::sub_match 的元素的容器, 可以通过与类 std::vector 相似的界面访问。 例如, 元素可以通过操作符 operator[]() 访问。

    另一方面,类boost::sub_match将迭代器保存在对应于正则表达式分组的位置。 因为它继承自类std::pair,迭代器引用的子串可以使用 first 和 second 访问。如果像上面的例子那样,只把子串写入标准输出流,那么通过重载操作符 << 就可以直接做到这一点,那么并不需要访问迭代器。

    请注意结果保存在迭代器中而boost::sub_match类并不复制它们, 这说明它们只是在被迭代器引用的相关字符串存在时才可以访问。

    另外,还需要注意容器boost::smatch 的第一个元素存储的引用是指向匹配正则表达式的整个字符串的,匹配第一组的第一个子串由索引 1 访问。

Boost.Regex 提供的第三个函数是 boost::regex_replace()。

#include <boost/regex.hpp> 
#include <locale> 
#include <iostream> 

int main() 
{ 
  std::locale::global(std::locale("German")); 
  std::string s = " Boris Schäling "; 
  boost::regex expr("\\s"); 
  std::string fmt("_"); 
  std::cout &l
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值