Z
Z
ZelibobA17062016-09-18 20:51:11
C++ / C#
ZelibobA1706, 2016-09-18 20:51:11

Why does regex only find one group?

Given a string with two floating point numbers, you need to parse the string and get both numbers from there. Decided to turn to regular expressions.

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

using namespace std;

int main()
{
    string s = "";

    getline(cin, s);

    regex rexp("([0-9]+[.][0-9]+)");
    smatch match;
    if(regex_search(s, match, rexp))
    {
        cout << "ms: " << match.size() << endl;
        for(int i = 0; i < match.size(); i++)
            cout << i << ".  " << match[i] << endl;
        cout << "Pr: " << match.prefix() << endl;
        cout << "Suf: " << match.suffix() << endl;
    }
    else cout << endl << "nope" << endl;

    return 0;
}

But for some reason it finds only one group. Why?
2bf5665341904c019819e87056016499.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2016-09-18
@ZelibobA1706

To search further, you need to call regex_search again (by moving the start of the search) until it returns false.
example from here
www.cplusplus.com/reference/regex/regex_search

// regex_search example
#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("this subject has a submarine as a subsequence");
  std::smatch m;
  std::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  std::cout << "Target sequence: " << s << std::endl;
  std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

Notice the while and s = m.suffix().str();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question