2

I want to get all substrings that match this expression: 1[0]+1

std::string str =  "0011011000001";
std::regex rx   ("1[0]+1");
std::smatch res;
std::regex_search(str, res, rx);
for (size_t i=0; i<res.size(); i++)
std::cout<<res[i]<<std::endl;

But it returns me only the first substring. What am I doing wrong?

1
  • Are you using g++ in c++11 mode? Std regexps are currently not yet supported in that implementation... Commented Oct 2, 2013 at 5:38

2 Answers 2

1

You should do this to get all substring:

while (std::regex_search (str,res,rx)) {
    std::cout <<res[0] << std::endl;
    str = res.suffix().str();
}

Or you can use std::regex_iterator to get all substrings as below:

std::regex_iterator<std::string::iterator> rit ( str.begin(), str.end(), rx);
std::regex_iterator<std::string::iterator> rend;

while (rit != rend) {
    std::cout << rit->str() << std::endl;
    ++rit;
}

But it will still output '101' and '1000001' when the string is "00110101000001" because the first match consumes part of the string. If you want to find all overlapping matches, then you need a regex implementation which supports Lookaround Assertion. Python does:

>>> re.findall(r'(?=(1[0]+1))', '00110101000001')
['101', '101', '1000001']

(?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

Sign up to request clarification or add additional context in comments.

Comments

0

Make the match non-greedy ...

std::regex rx   ("(1[0]+1)?");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.