12

我现在正在尝试从头开始学习一些 C++。
我精通python、perl、javascript,但过去只是在课堂环境中短暂接触过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;
}

4

4 回答 4

17

boost 库通常是一个不错的选择,在本例中为Boost.Regex。甚至还有一个将字符串拆分为已经可以满足您要求的标记的示例。基本上它归结为这样的事情:

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;
}
于 2009-06-14T05:05:04.150 回答
2

如果你想尽量减少迭代器的使用,并精简你的代码,以下应该可以工作:

#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;   
  }

}
于 2009-06-14T05:38:11.450 回答
1

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

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

于 2009-06-14T04:41:04.317 回答
1

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

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

C++ TR1 正则表达式入门

Visual C++ 标准库:TR1 正则表达式

于 2009-06-14T10:42:28.973 回答