LonelyCpp
LonelyCpp

Reputation: 2673

How would you write a regex to match the largest sequence of 0's in a string?

If the input is

11100011100000011

the largest sequence of 0's is at

000000 (pos: 9)

I tried

regex re0("(.*)([0]+)(.*)");

regex_search(sch, m, re0);
for (unsigned i = 0; i<m.size(); ++i) {
    std::cout << "match " << i << " (" << m[i] << ") ";
    std::cout << "at position " << m.position(i) << std::endl;  
}

But it gives my wrong results

11100011100000011
match 0 (11100011100000011) at position 0
match 1 (11100011100000) at position 0
match 2 (0) at position 14
match 3 (11) at position 15

How do you make the [0]+ greedy to find the largest match?

Upvotes: 2

Views: 165

Answers (1)

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

The longest series of zeros is that that is not followed (not necessarily immediately) by at least the same sequence of zeros:

(0+)(?!.*\1)

Regex demo: https://regex101.com/r/G0FieA/2

C++:

regex re0("(0+)(?!.*\\1)");
if (regex_search(sch, m, re0)) {
    std::cout << "match '" << m[0] << "' ";
    std::cout << "at position " << m.position(0) << std::endl;  
}

Full demo: https://ideone.com/PnFrMq

Upvotes: 2

Related Questions