使用regex来解析数字

问题描述 投票:-2回答:1

我的问题是不言自明的,我想写一个regex来从用户通过控制台输入的字符串中解析出数字。我采用用户输入的方式。

getline(std::cin,stringName); //1 2 3 4 5

我假设用户输入了N个数字,除了最后一个数字外,后面都有空格。我已经通过分析字符串char逐个分析解决了这个问题,就像这样。

std::string helper = "";
        std::for_each(stringName.cbegin(), strinName.cend(), [&](char c)
            {

                if (c == ' ')
                {
                   intVector.push_back(std::stoi(helper.c_str())); 
                    helper = "";
                }
                else
                    helper += c;
            });
        intVector.push_back(std::stoi(helper.c_str()));

我想通过使用regex实现同样的行为。我写了以下代码。

std::regex rx1("([0-9]+ )");
        std::sregex_iterator begin(stringName.begin(), stringName.end(), rx1);
        std::sregex_iterator end;
        while (begin != end) 
        {
            std::smatch sm = *begin;
            int number = std::stoi(sm.str(1));
            std::cout << number << " ";

        }

这个regex的问题发生在最后一个数字的时候 因为它后面没有空格,所以它进入了一个无限循环。谁能给我一个解决这个问题的方法?

c++ regex string parsing regex-group
1个回答
1
投票

你会得到一个无休止的循环,因为你从来没有递增过。begin. 如果你这样做,你会得到所有的数字,除了最后一个(如你所说,后面没有空格)。

但我不明白为什么你觉得有必要在正则表达式中加入空格。如果你只是匹配一串数字,正则表达式会自动选择最长的匹配项,所以后面的字符(如果有的话)不可能是数字。

我在regex中也没有看到捕捉的价值。如果你想将捕获限制在数字本身,你应该使用 ([0-9]+). (但由于 stoi 只有在找到一个非数字之前才会进行转换,这并不重要)。)

所以你就用这个。

std::regex rx1("[0-9]+");
for (auto it = std::sregex_iterator{str.begin(), str.end(), rx1},
          end = std::sregex_iterator{};
     it != end;
     ++it) {
    std::cout << std::stoi(it->str(0)) << '\n';
}          

(活在科利鲁上)

© www.soinside.com 2019 - 2024. All rights reserved.