zoukankan      html  css  js  c++  java
  • Quick Start for C++ TR1 Regular Expressions

    Introduction

    Regular expression syntax is fairly similar across many environments. However, the way you use regular expressions varies greatly. For example, once you've crafted your regular expression, how do you use it to find a match or replace text? It's easy to find detailed API documentation, once you know what API to look up. Figuring out where to start is often the hardest part.

     

    How Do I Do a Match?

    Construct a regex object and pass it to regex_search.

    std::string str = "Hello world";
    std::tr1::regex rx("ello");
    assert( regex_search(str.begin(), str.end(), rx) );

    The function regex_search returns true because str contains the pattern ello. Note that regex_match would return false in the example above because it tests whether the entire string matches the regular expression. regex_search behaves more like most people expect when testing for a match.

    How Do I Retrieve a Match?

     Use a form of regex_search that takes a match_result object as a parameter.

    For example, the following code searches for <h> tags and prints the level and tag contents.

    std::tr1::cmatch res;
    str = "<h2>Egg prices</h2>";
    std::tr1::regex rx("<h(.)>([^<]+)");
    std::tr1::regex_search(str.c_str(), res, rx);
    std::cout << res[1] << ". " << res[2] << "\n";

    This code would print 2. Egg prices. The example uses cmatch, a typedef provided by the library for match_results<const char* cmatch>.

    How Do I Do a Replace?


    Use regex_replace.

    The following code will replace “world” in the string “Hello world” with “planet”. The string str2 will contain “Hello planet” and the string str will remain unchanged.

    std::string str = "Hello world";
    std::tr1::regex rx("world");
    std::string replacement = "planet";
    std::string str2 = std::tr1::regex_replace(str, rx, replacement);

    Note that regex_replace does not change its arguments, unlike the Perl command s/world/planet/. Note also that the third argument to regex_replace must be a string class and not a string literal.

    from:http://www.codeproject.com/Articles/26285/Quick-Start-for-C-TR1-Regular-Expressions

  • 相关阅读:
    es5中,一个在js中导入另一个js文件。
    移动端字体小于12号字的时候,line-height居中的问题
    初学者都能懂得 Git 说明
    一探 Vue 数据响应式原理
    文件的命名规则
    Vue 的 watch 和 computed 有什么关系和区别?
    MVC 与 Vue
    博客园皮肤设置
    java使用run和start后的线程引用
    Python改变一行代码实现二叉树前序、中序、后序的迭代遍历
  • 原文地址:https://www.cnblogs.com/ytjjyy/p/2757365.html
Copyright © 2011-2022 走看看