0

I'm trying to extract all numbers (positive and negative) with 4 to 5 digits from a string. To do so, I'm using the following code:

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string test_string("S: 0 2 -1500 -1500 0 -10000 10000");
    std::smatch match_results;
    std::regex rgx("-?[0-9]{4,5}");
    std::regex_search(test_string,match_results,rgx);
    std::cout<<match_results.str(0)<<' '<<match_results.str(1)<<' '<<std::endl;
    return 0;
}

I would expect this code to output

-1500 -1500

Instead the output is only

-1500

Outputting the 3rd and 4th match doesn't work either.

Testing the regular expresion on the exact same teststring on regex101.com yields all for numbers with more than 3 digits.

What am I doing wrong here?

Max
  • 1,471
  • 15
  • 37
  • 1
    Use the `sregex_iterator` / `sregex_token_iterator` to get all matches ([example here](https://stackoverflow.com/a/32765645/3832970)). – Wiktor Stribiżew Jun 06 '21 at 19:27
  • 1
    This behaviour is described at [cppreference](https://en.cppreference.com/w/cpp/regex/regex_search), especially in the notes: *'In order to examine all matches within the target sequence, std::regex_search may be called in a loop, restarting each time from m[0].second of the previous call. [...]'* – Aconcagua Jun 06 '21 at 19:29

0 Answers0