简体   繁体   English

C ++ [std :: regex]试图只匹配中间带空格的数字

[英]C++ [std::regex] trying to match only numbers with spaces in between

I'm working on a card game in C++ where I want to get some user input via getline(). 我正在使用C ++开发卡片游戏,我希望通过getline()获得一些用户输入。 The input needs to be in this specific format: 输入需要采用以下特定格式:

"1 2 3 4 5 6" “1 2 3 4 5 6”

The range of numbers is 1-11 and each number must be seperated with a space. 数字范围是1-11 ,每个数字必须用空格分隔。 The user is putting in index numbers for a vector. 用户正在为矢量输入索引号。 Say he writes "1 2 3" and hits enter, position 0, 1 and 2 are being adressed by the vector. 假设他写了“1 2 3”并命中输入,位置0,1和2正被矢量压缩。

I'm also open for any other recommendations considering the design decision to let the user input the vector (or essentially their card's) position. 考虑到设计决定让用户输入向量(或基本上是他们的卡片)的位置,我也对任何其他建议持开放态度。

The player cards are displayed in this format "1 blue" and are stored as strings in a vector. 播放器卡以“1蓝色”格式显示,并以字符串形式存储在矢量中。 I figured it is too much hassle for the user to input the whole card name, so I chose to use the vector index. 我认为用户输入整个卡片名称太麻烦了,所以我选择使用矢量索引。

Below is the code snippet of my regex string. 下面是我的正则表达式字符串的代码片段。 It works, kinda. 它有效,有点。 It just pushes the whole string in the vector, missing the 10. But I don't need 1 vector element like this: "1 2 3 4", I need 4 vector elements with every number being one element. 它只是将整个字符串推入向量中,错过了10.但我不需要像这样的1个向量元素:“1 2 3 4”,我需要4个向量元素,每个数字都是一个元素。

Things that shouldn't match: 不应该匹配的事情:

"1234567" “1234567”

"abcdef" “ABCDEF”

"12 34 567 32" “12 34 567 32”

If you need any further context, I will gladly provide so. 如果您需要任何进一步的背景,我很乐意提供。

Thanks in advance 提前致谢

int main()
{
    int i = 0;

    std::regex rx("([[:digit:]]\\s)+([[:digit:]]\\s)+");
    std::string line = "1 2 3 4 5 6 7 8 9 10";
    std::smatch m;
    std::vector<std::string> catchit;

    while (regex_search(line, m, rx))
    {
        std::cout << "Pattern found " << m[i] << '\n';
        catchit.push_back(m[i]);
        line = m.suffix().str();
        i++;
    }
    return 0;
}

This solves my problem without having to use regex, thank you very much @Nick 这解决了我的问题,而不必使用正则表达式,非常感谢@Nick

Why not std::cin? 为什么不std :: cin? Or wrap your output from getline in a std::stringstream and use operator>> to read numbers one at a time and validate them then? 或者将getline的输出包装在std :: stringstream中,并使用operator >>一次读取一个数字然后验证它们? Eg std::stringstream stream(line); 例如std :: stringstream stream(line); /* loop */ stream >> val; / * loop * / stream >> val; if (val < 0 || val > 11)... if(val <0 || val> 11)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM