C++11 正则表达式——实例3

下面一个例子将进行年月日格式的转换,将DD-MM-YYYY –> YYYY-MM-DD,其中‘.’或者‘/’都能正确识别。

 

#include <regex>

#include <iostream>

#include <string>

 

std::string format_date(const std::string& date)

{

   // regular expression

   const std:: regex pattern("(\\d{1,2})(\\.|-|/)(\\d{1,2})(\\.|-|/)(\\d{4})");

 

   // transformation pattern, reverses the position of all capture groups

   std::string replacer = "$5$4$3$2$1";

 

   // apply the tranformation

   return std:: regex_replace(date, pattern, replacer);

}

 

int main()

{

   std::string date1 = "1/2/2008";

   std::string date2 = "12.08.2008";

 

   std::cout << date1 << " -> " << format_date(date1) << std::endl;

   std::cout << date2 << " -> " << format_date(date2) << std::endl;

   std::cout << std::endl;

   return 0;

}

运行结果:

说明,这个例子也很有实用价值,这里用到的正则表达式的匹配模式前面都已经进行过说明就不在分析。

 

相信通过以上例子,对正则表达式的运用已经有了一个不错的了解,下面再来添加一个实例,加深一下理解。

下面一个例子用来查找给定文本中new的个数和delete的个数是否相等:

#include <iostream>

#include <string>

#include <regex>

 

 

int main() {

// "new" and "delete" 出现的次数是否一样?

    std::regex reg("(new)|(delete)");

    std::smatch m;

    std::string s=

    "Calls to new must be followed by delete. \

    Calling simply new results in a leak!";

    int new_counter=0;

    int delete_counter=0;

    std::string::const_iterator it=s.begin();

    std::string::const_iterator end=s.end();

   

    while (std::regex_search(it,end,m,reg))

    {

        // 是 new 还是 delete?

        m[1].matched ? ++new_counter : ++delete_counter;

        it=m[0].second;

    }

   

    if (new_counter!=delete_counter)

    std::cout << "Leak detected!\n";

    else

    std::cout << "Seems ok...\n";

    std::cout << std::endl;

}

运行结果:

运行结果表明,new和delete的数量不相等,也就是发生了“内存泄露”。

为了帮助理解,上面对于match_results类型的下标操作的意义,请看ISOIEC14882 C++11的说明:

#include <iostream>

#include <string>

#include <regex>

using namespace std;

 

class regex_callback {

  int sum_;

public:

  regex_callback() : sum_(0) {}

 

  template <typename T> void operator()(const T& what) {

    sum_+=atoi(what[1].str().c_str());

  }

 

  int sum() const {

    return sum_;

  }

};

 

int main() {

    regex reg("(\\d+),?");

    string s="1,1,2,3,5,8,13,21";

 

    sregex_iterator it(s.begin(),s.end(),reg);

    sregex_iterator end;

 

    regex_callback c;

    int sum=for_each(it,end,c).sum();//for_each返回的是这个函数对象,因此可以调用sum

   

    cout<<sum<<endl;

    cout<<endl;

}

运行结果:

#include <iostream>

#include <string>

#include <regex>

using namespace std;

int main()

{

        regex reg("/");

        vector<std::string> vec;

        string s="Split/Vulue/Teather/Neusoft/Write/By/Lanwei";

        sregex_token_iterator it(s.begin(),s.end(),reg,-1);//// -1逆向匹配,就是匹配除了'/'之外的

        sregex_token_iterator end ;

        while(it!=end)

            vec.push_back(*it++);

        copy(vec.begin(),vec.end(),ostream_iterator<std::string>( cout,"\n"));

}

运行结果:

 

 

posted @ 2012-04-08 23:27  KingsLanding  阅读(7167)  评论(0编辑  收藏  举报