@ZelibobA1706

Почему regex находит только одну группу?

Дана строка с двумя числами с плавающей точкой, нужно распарсить строку и достать оттуда оба числа. Решил обратиться к регулярным выражениям.
#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;
}

Но находит почему-то только одну группу. Почему?
2bf5665341904c019819e87056016499.png
  • Вопрос задан
  • 285 просмотров
Решения вопроса 1
15432
@15432
Системный программист ^_^
Для дальнейшего поиска нужно снова вызывать regex_search (передвинув начало поиска), пока он не вернёт false.

пример отсюда
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;
}


Обратите внимание на while и s = m.suffix().str();
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы