Home > Blockchain >  pattern search in text strings in c
pattern search in text strings in c

Time:11-08

I just want look for a pattern in a string. for example for this "abaxavabaabcabbc" string the app should print "abc" and "abbc". So, the pattern should have "abc" but the numbers of "b" are changing. pattern => "abc" => the numbers of "b" are changeable. And the programm should be in c .

CodePudding user response:

There is only one answer to this question. You MUST use a std::regex. Regular expressions are exactly made for this purpose.

C supports also regular expressions. Please see here

The regex "ab c" will match all strings starting with an "a", having one or more "b" and end with a "c"

See the following very short program:

#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"));
}

This program will iterate over all matched patterns and copy them to std::cout

CodePudding user response:

Using regex_search instead of the iterator:

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";
        }
    }
}

Prints

Match: abc
Match: abbc
  • Related