1

Example input

abc55def789KK23GOOD9999910ONEM109ORE19k6 

Output

789 109 

Example input

abcdef 

Output

-1 

This is what I need to achieve via the regex code.

I have gone through numerous websites for tutorials but couldn't decipher it as needed.

My idea was to use this regex

rx("[0-9][0-9][0-9]""\\-""[0-5][0-5]") 

But then I couldn't understand the smatch flag and how to retrieve the results.

1
  • Try rx(R"((?:^|\D)(\d{3})(?!\d))") Commented Jun 22, 2017 at 10:50

1 Answer 1

1

Here is a sample C++ demo showing how to extract 3 digit chunks not enclosed with other digits:

#include <string> #include <iostream> #include <regex> using namespace std; int main() { std::regex r(R"((?:^|\D)(\d{3})(?!\d))"); std::string s = "abc55def789KK23GOOD9999910ONEM109ORE19k6"; // "abcsd"; => Not Found if (regex_search(s, r)) { for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r); i != std::sregex_iterator(); ++i) { std::smatch m = *i; std::cout << m[1].str() << '\n'; } } else { std::cout << "Not found" << '\n'; } return 0; } 

See the regex demo. The pattern matches:

  • (?:^|\D) - a start of a string or any non-digit (the (?:...) is a non-capturing group that consumes the text matched with its pattern - we have to use it since C++ std::regex does not support lookbehinds - and thus the following caprturing group ((\d{3})) will have an ID of 1, not 2)
  • (\d{3}) - Group 1: any 3 digits
  • (?!\d) - the 3 digits captured should not be followed with a digit (this (?!...) is a negative lookahead that checks if a pattern matches immediately to the right of the current location without putting the matched text into the match).

The m[1].str() is used to access the value captured into Group 1.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.