简体   繁体   English

正则表达式不起作用 C++

[英]Regular Expression not working C++

im trying to use a regular expression to ensure the heading entered for an aircraft is between o and 360, but i cant get it to work.我试图使用正则表达式来确保为飞机输入的航向在 o 和 360 之间,但我无法让它工作。

std::regex headingCheck{"^([0-9]|1[0-9]2[0])$"};
    bool match = false;
    while (!match)
    {
        if (std::regex_match(heading, headingCheck))
        {
            heading_ = heading;
        }
        else
        {
            std::cout << "Invalid heading, can only be between 0 and 360 degrees" << std::endl;
        }
    }

# #

//Heading can only be between 0-360?
    if (heading >= 0 && heading <= 360)
    {
        heading_ = heading;
    }
    else
    {
        std::cout << "Incorrect heading, heading can only be between 0 and 360" << std::endl;
    }

Should i do this instead?我应该这样做吗? Is it as accurate/reliable?它是否准确/可靠?

If you still want regex (though this is not optimal) you can use the following expression:如果您仍然需要正则表达式(尽管这不是最佳的),您可以使用以下表达式:

std::regex re{ "^[0-9]$|^[1-9][0-9]$|^[1-2][0-9][0-9]$|^3[0-5][0-9]$|^360$" };
std::string headings[5] = { "0","15","390","360","23883" };

for (int i = 0; i < 5; ++i)
    std::cout << "Heading " << headings[i] << " is " << (std::regex_match(headings[i], re) ? "valid" : "invalid") << std::endl;

First part matches 0-9, second part matches 10-99, third part matches 100-299, fourth part matches 300-359, last matches 360. Prints:第一部分匹配 0-9,第二部分匹配 10-99,第三部分匹配 100-299,第四部分匹配 300-359,最后匹配 360。打印:

Heading 0 is valid
Heading 15 is valid
Heading 390 is invalid
Heading 360 is valid
Heading 23883 is invalid

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

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