c++ - Boost正则表达式拆分遗漏了最后一个词

标签 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

最佳答案

你的最后一个词后面跟着 $ 而不是 \\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/

相关文章:

c++ - 比较 C++ 中的两个浮点变量

用于以字母数字和连字符开头的正则表达式,在字符串后面加下划线

c++ - 将文本附加到正则表达式匹配的一部分

c++ - boost::circular_buffer 是否确认自动弹出操作

c++ - 确定套接字中的可用字节数

c++ - 如何传递参数来 boost asio async_accept

c++ - 无法将焦点设置到 CEdit 控件

c++ - 将元素添加到现有结构会使函数因段错误而崩溃

c++ - 将 ostream 重定向到输出文件

Java Regex - 删除数学运算符后的剩余部分