0

new to regex,

what is the correct regex form I should use in order to get all occurrences of Cat (case sensitive) within the following string at any position and surrounding characters (or whitespaces)

std::string s(" Cat CatCat CCatt CatcatCat Cat");
std::regex e("(.*)(Cat)(.*)");
std::smatch sm;    
std::regex_match (s,sm,e);
std::cout << "there's " << sm.size() << " Cats\n";

I get "there's 4 Cats", when it should be 7 Cats. I'm missing 3 Cats. :)

Thanks in advance.

  • thanks for pointing that out, it kinda helped me reading the following from a comment : `regex_match` "secretly" surrounds your pattern with `^yourpatternhere$` – user3374479 Oct 04 '15 at 15:22
  • 1
    And then you get `sm.size()` equal `4`, because 1st match is the whole matched substring and there are 3 submatches - `.*`, `Cat` and `.*`. You should use `std::regex_search` in a condition of a `while` loop and change regex pattern to `"Cat"`. – LogicStuff Oct 04 '15 at 15:26
  • too bad I have to use a while loop when the above looks tight and elegant – user3374479 Oct 04 '15 at 15:31
  • 1
    You can also take a look at [this](http://stackoverflow.com/questions/8283735/count-number-of-matches). Without a loop. – LogicStuff Oct 04 '15 at 15:33
  • 1
    sweet. Thanks @LogicStuff :) – user3374479 Oct 04 '15 at 15:37

0 Answers0