【问题标题】:pattern search in text strings in c++C++中文本字符串中的模式搜索
【发布时间】:2021-12-20 19:55:16
【问题描述】:

我只想在字符串中查找模式。例如对于这个“abaxavabaabcabbc”字符串,应用程序应该打印“abc”和“abbc”。所以,模式应该有“abc”,但“b”的数字正在改变。 pattern => "abc" => "b" 的数字是可变的。 而且程序应该是c++。

【问题讨论】:

  • 所以你只是在寻找a,然后是至少一个b,然后是一个c?
  • 你知道什么是“正则表达式”吗?

标签: c++ algorithm


【解决方案1】:

使用 regex_search 代替迭代器:

Live On Coliru

#include <regex>
#include <string>
#include <iostream>

int main() {
    std::regex const pattern("ab+c");
    for (std::string const text :
         {
             "abaxavabaabcabbc",
         }) //
    {
        std::smatch match;
        for (auto it = text.cbegin(), e = text.cend();
             std::regex_search(it, e, match, pattern); it = match[0].second) {
            std::cout << "Match: " << match.str() << "\n";
        }
    }
}

打印

Match: abc
Match: abbc

【讨论】:

    【解决方案2】:

    这个问题只有一个答案。您必须使用std::regex。正则表达式正是为此目的而制作的。

    C++ 也支持正则表达式。请看here

    正则表达式“ab+c”将匹配所有以“a”开头、包含一个或多个“b”并以“c”结尾的字符串

    请看以下非常简短的程序:

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <iterator>
    #include <regex>
    
    const std::regex re{ R"(ab+c)" };
    using Iter = std::sregex_token_iterator;
    
    int main() {
        const std::string test{ "abaxavabaabcabbc" };
    
        std::copy(Iter(test.begin(), test.end(), re), Iter(), std::ostream_iterator<std::string>(std::cout, "\n"));
    }
    

    这个程序将遍历所有匹配的模式并将它们复制到std::cout

    【讨论】:

    • 我绝不会说他必须为此使用std::regex。为此目的,它可能会很慢(尤其是使用正则表达式的编译时间会更长)并且定义他自己的函数,该函数将首先递归查找此类表达式可能会更快。尽管如此,使用内置的正则表达式是查找它的最快方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2012-10-01
    • 2021-11-24
    • 2012-11-01
    相关资源
    最近更新 更多