【发布时间】:2010-11-02 19:01:45
【问题描述】:
目前我正在尝试从头开始学习一些 C++。
我精通 python、perl、javascript,但只在
过去的课堂设置。请原谅我的问题太天真了。
我想使用正则表达式拆分字符串,但没有找到太多运气 一个清晰、明确、高效且完整的示例,说明如何在 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;
}
【问题讨论】:
-
查看 Boost.Regex。我想你可以在这里找到答案:stackoverflow.com/questions/181624/…
-
您应该添加“我自己找到”部分作为您自己问题的答案,而不是让它成为您问题的一部分......尽管提到您找到它并发布了答案。如果其他人发现这个问题很有用......他们会希望看到社区选择的答案以及您选择的答案。您的回答可能不是社区的最佳选择。