我正试图从头开始学习一些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
Run Code Online (Sandbox Code Playgroud)
我想知道如何最好地完成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;
}
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 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;
}
Run Code Online (Sandbox Code Playgroud)