-1

Here's my code:

int main()
{
    string s = "abc1010101bca10";
    int c = 0;
    string subject(s);
    try {
        regex re("10+1");
        sregex_iterator next(subject.begin(), subject.end(), re);
        sregex_iterator end;
        while (next != end) {
            smatch match = *next;
            cout << match.str() << "\n";
            c++;
            next++;
        }
    }
    catch (std::regex_error& e) {
        cout << "Error in regex\n";
    }
    cout << c << "\n";
    return 0;
}

I am trying to find the occurrence of 1{0}+1 in my string.

For input : abc1010101bca10

Output count should be 3 but above code gives it as 2.

I think sregex_iterator causing problem here as it directly skips matched string.

Current output:

101
101
2

It should be: 101 101 101 3

Please let me know, where I am going wrong.

Azeem
  • 11,148
  • 4
  • 27
  • 40
Nagendra Nigade
  • 866
  • 2
  • 12
  • 28
  • 2
    A regular expression shouldn't match the same part of a string multiple times. This is the expected behavior and how all regex engines I'm aware of work. See, e.g.: this example on regex101: https://regex101.com/r/u1jGN2/1 – UnholySheep Aug 25 '18 at 11:21

1 Answers1

-1

The output should be 2. Look at how the regular exprssion applies. The first match is

abc1010101bca10

the text after the first match is

0101bca10

so the next match is the "101" in that fragment, which, in the original text, is

abc1010101bca10

Pete Becker
  • 74,985
  • 8
  • 76
  • 165