代码之家  ›  专栏  ›  技术社区  ›  Anonymous

C++使用正则表达式标记字符串

  •  11
  • Anonymous  · 技术社区  · 15 年前

    我正试着从零开始学习一些C++。
    我精通Python、Perl、JavaScript,但在C++中只遇到了C++。 过去的课堂环境。请原谅我的问题太幼稚。

    我想用正则表达式拆分一个字符串,但找不到太好的结果 一个明确的,明确的,有效的和完整的例子,如何做到这一点在C++中。

    在Perl中,这是一种常见的操作,因此可以用一种微不足道的方式完成。

    /home/me$ cat test.txt
    this is  aXstringYwith, some problems
    and anotherXY line with   similar issues
    
    /home/me$ cat test.txt | perl -e'
    > while(<>){
    >   my @toks = split(/[\sXY,]+/);
    >   print join(" ",@toks)."\n";
    > }'
    this is a string with some problems
    and another line with similar issues
    

    我想知道如何最好地完成C++中的等价项。

    编辑:
    我想我在Boost库中找到了我想要的东西,如下所述。

    boost regex-token-iterator (为什么不强调工作?)

    我想我不知道该找什么。

    
    #include <iostream>
    #include <boost/regex.hpp>
    
    using namespace std;
    
    int main(int argc)
    {
      string s;
      do{
        if(argc == 1)
          {
            cout << "Enter text to split (or \"quit\" to exit): ";
            getline(cin, s);
            if(s == "quit") break;
          }
        else
          s = "This is a string of tokens";
    
        boost::regex re("\\s+");
        boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
        boost::sregex_token_iterator j;
    
        unsigned count = 0;
        while(i != j)
          {
            cout << *i++ << endl;
            count++;
          }
        cout << "There were " << count << " tokens found." << endl;
    
      }while(argc == 1);
      return 0;
    }
    
    
    5 回复  |  直到 15 年前
        1
  •  16
  •   sth    15 年前

    Boost.Regex . 甚至有 an example 用于将字符串拆分为已执行所需操作的标记。基本上是这样的:

    boost::regex re("[\\sXY]+");
    std::string s;
    
    while (std::getline(std::cin, s)) {
      boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
      boost::sregex_token_iterator j;
      while (i != j) {
         std::cout << *i++ << " ";
      }
      std::cout << std::endl;
    }
    
        2
  •  3
  •   Community CDub    7 年前

    查看boost.regex。我想你可以在这里找到答案:

    C++: what regex library should I use?

        3
  •  2
  •   Faisal Vali    15 年前

    如果您希望最小化迭代器的使用,并简化代码,那么应该使用以下方法:

    #include <string>
    #include <iostream>
    #include <boost/regex.hpp>
    
    int main()
    {
      const boost::regex re("[\\sXY,]+");
    
      for (std::string s; std::getline(std::cin, s); ) 
      {
        std::cout << regex_replace(s, re, " ") << std::endl;   
      }
    
    }
    
        4
  •  1
  •   Employed Russian    15 年前

    与Perl不同的是,正则表达式不是“内置”到C++中。

    您需要使用外部库,例如 PCRE .

        5
  •  1
  •   anno    15 年前

    正则表达式是包含在Visual C++ 2008 SP1(包括Express版)和G+ 4.3中的Tr1的一部分。

    页眉是 <regex> 和命名空间std::tr1。与STL一起工作很好。

    Getting started with C++ TR1 regular expressions

    Visual C++ Standard Library : TR1 Regular Expressions