zoukankan      html  css  js  c++  java
  • #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

    正则表达式检索

     1 #include <iostream>
     2 #include <boost/regex.hpp>
     3 
     4 void main()
     5 {
     6     std::string str = "chinaen 8Glish";
     7 
     8     boost::regex expr("(\w+)\s(\w+)");
     9 
    10     //+ 用来表示重复一或多次
    11     //d-digit 任何0-9之间的数字
    12     //s-space 任何空格字符
    13     //u-upper A-Z之间的大写字母。如果设置了地域的话,可能包含其他字符
    14     //w-word 任何单词字符-字母数字下划线
    15 
    16     std::cout << boost::regex_match(str, expr) << std::endl;//匹配1,不匹配0
    17 
    18     boost::smatch what;
    19 
    20     if (boost::regex_search(str, what, expr))//正则表达式检索
    21     {
    22         std::cout << what[0] << std::endl;
    23         std::cout << what[1] << std::endl;
    24         std::cout << what[2] << std::endl;
    25         std::cout << what[3] << std::endl;
    26     }
    27     else
    28     {
    29         std::cout << "检索失败" << std::endl;
    30     }
    31 }

    boost::regex_replace

    正则表达式替换

    //s-space 任何空格字符

     1 #include <iostream>
     2 #include <boost/regex.hpp>
     3 
     4 void main()
     5 {
     6     std::string str = "chinaen 8Glish";
     7 
     8     boost::regex expr("\s");//s-space 任何空格字符
     9 
    10     std::string tihuan = "____";
    11 
    12     std::cout << boost::regex_replace(str, expr, tihuan) << std::endl;//把expr替换
    13 }
  • 相关阅读:
    JAVA基础之(十三)“集合”
    JAVA基础之(十二)“泛型”
    JAVA基础之(五)”继承“
    算法--验证时间段不交叉/不重复的方法
    工具类--常量类
    工具--常见eclipse配置导入web工程(tomcat容器)步骤
    jar包--POI.jar包使用问题汇总
    java中常忽视的小问题
    ResultSetMetaData
    PreparedStatement
  • 原文地址:https://www.cnblogs.com/denggelin/p/5769624.html
Copyright © 2011-2022 走看看