如何使用增强正则表达式在单行中匹配单词

how to match word in single line using Boost Regex?

本文关键字:单词 单行中 何使用 增强 正则表达式      更新时间:2023-10-16

我有四个单词,在一行中,用n分隔。 例如:"aane'sboobng-coonoodnff" (注意,单词可能不仅包含英文字母,但不包含""!

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

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

我正在使用Boost Regex:

#include <iostream>
#include <string>
#include <boost/regex.hpp>
int main()
{    
    std::vector<std::string> v; 
    std::string text = "aane'sboobng-coonoodnff";
    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有人的建议更新源。

非常感谢

当你想要[a-z]*时,不要在你的正则表达式中使用.*

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

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

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

谢谢。

bw*oow*b应该会有所帮助。 Perl 正则表达式语法。

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

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

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

编译、运行并得到:

boob
coo
ood
total find: 3