如何使用Boost Regex在单行中匹配单词?

时间:2013-10-15 11:57:26

标签: c++ regex boost

我在一行中有四个单词,由 \n 分隔。例如:"aa\ne'sboob\ng-coo\nood\nff"(注意,单词不仅可能包含英文字母,而且不包含'\ n'!)

我想在单词级别进行部分匹配:例如。部分匹配"oo"给了我"boob", "coo", and "ood"

我从模式"^(.*?oo.*?)$"开始,它给了我:"aa\ne'sboob", "g-coo", and "ood"。显然"aa\ne'sboob"是错误的。

我正在使用Boost Regex:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main()
{    
    std::vector<std::string> v; 
    std::string text = "aa\ne'sboob\ng-coo\nood\nff";

    const char* pattern = "^(.*?oo.*?)$";
    boost::regex reg(pattern);
        boost::sregex_iterator it(text.begin(), text.end(), reg);
        boost::sregex_iterator end;
    std::string tmp;
        for (; it != end; ++it) {
        tmp = it->str();
        v.push_back(it->str());
            std::cout << tmp << std::endl;
        }
    std::cout << "total find: " << v.size() << std::endl;
    return 0;
}

请帮帮我吗?

修改: 我有一个模式工作,但我不明白。还请帮忙解释一下。 注意:也许我需要帮助正确使用Boost正则表达式。

修改: 澄清这些单词不仅可能包含英文字母。还要将源更新为@ just-somebody建议。

非常感谢

3 个答案:

答案 0 :(得分:0)

如果需要.*

,请勿在正则表达式中使用[a-z]*

答案 1 :(得分:0)

我有这个模式对我来说很好:

"^([^\\n.]*?oo.*?)$"

但我期待更优雅的解决方案。

谢谢。

答案 2 :(得分:0)

\b\w*oo\w*\b应该有所帮助。 Perl Regular Expression Syntax

编辑,因为OP争辩答案......

我对发布的代码进行了以下更改:

  • 添加了#include <boost/regex.hpp>
  • 将功能更改为int main(void)
  • 将模式更改为const char* pattern = "\\b\\w*oo\\w*\\b";

编译,运行并获得:

boob
coo
ood
total find: 3