提升正则表达式分裂错过了最后一个字

时间:2013-02-18 22:52:40

标签: c++ regex boost

我试图使用Boost :: regex将句子分成单个单词。 但它不打印最后一个字。 有什么想法是错的吗?

代码是:

#include <iostream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;

int main() {
smatch matchResults;
regex whiteChars("(.*?)[\\s]");
string p = "This is a sentence";
for(string::const_iterator sit = p.begin(), sitend = p.end(); sit != sitend;)
{
    regex_search(sit, sitend, matchResults, whiteChars);
    if(matchResults[1].matched)
        cout << matchResults[1] << endl;
    sit = matchResults[0].second;
}
return 0;
}

Output: 
This 
is 
a
Expected Output: 
This 
is 
a
sentence

2 个答案:

答案 0 :(得分:3)

您的最后一个单词后跟$而非\\s,因此您当前的正则表达式 - "(.*?)[\\s]"将与之匹配。

你可以试试这个:

"(.*?)(?:\\s|$)"

甚至更好,这也可能有效:

([^\\s]*)  // Just get all the non-space characters. That is what you want

答案 1 :(得分:0)

std::regex rgx("\\s");
std::string p("This is a sentence");
std::regex_token_iterator current(p.begin(), p.end(), rgx, -1);
std::regex_token_iterator end;
while (current != end)
    std::cout << *current++ << '\n';

这也适用于Boost的正则表达式。我还没有编写那段代码,因为我不了解Boost的细节。