MrRobot9 - 1 year ago 83
C++ Question

# Finding matches in c++

I have a string consisting of 1s and 0s, for example

`11101010101011101`
, I need to find index where repetitive
`01`
starts and ends.In this example its 3 and 12

``````      `1  1  1  0  1  0  1  0  1  0  1  0  1  1  1  0  1`
^------REPETITIVE 01-------^
Starts here                Ends here
``````

How do I find the indexes 3 and 12

``````string str = "11101010101011101";
regex rx("01+");

vector<int> index_matches; // results saved here
// (should be {2, 8}, but always get only {2})

for(auto it = std::sregex_iterator(str.begin(), str.end(), rx); it != std::sregex_iterator(); ++it)
index_matches.push_back(it->position());

for(int n: index_matches)
{
std::cout << n << '\n';
}
``````

Tried this, but it returns 3,5,7,9,11 and returns 15 too,but I dont want that. Is there a way I can come to know where difference of 2 gets broken, like difference between 15 and 11 is 4 so ignore 15.

If you want the longest match, you need to use a greedy version of regex, also you need braces `(01)+` otherwise you are searching for 01111.... etc.

You can try the following out here, it outputs

Success time: 0 memory: 16168 signal:0

(3, 12)

(15, 16)

``````#include <iostream>
#include <regex>
using namespace std;

int main() {
string str = "11101010101011101";
regex rx("(01)+", std::regex::extended);

vector<pair<int, int>> index_matches; // results saved here

for(auto it = std::sregex_iterator(str.begin(), str.end(), rx); it != std::sregex_iterator(); ++it) {

std::smatch match = *it;
index_matches.push_back(make_pair<int, int>(it->position(), it->position() + match.length() -1));
}

for(auto n: index_matches)
std::cout << "(" << n.first << ", " << n.second << ")" << std::endl;

return 0;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download