我正在尝试使用 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
最佳答案
你的最后一个词后面跟着 $
而不是 \\s
,所以你当前的正则表达式 - "(.*?)[\\s]"
不会匹配它。
你可以试试这个:
"(.*?)(?:\\s|$)"
甚至更好,这也可能有效:
([^\\s]*) // Just get all the non-space characters. That is what you want
关于c++ - Boost正则表达式拆分遗漏了最后一个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946768/