我现在正在尝试从头开始学习一些 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;
}