我试图使用正则表达式来确保为飞机输入的航向在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;
}
我应该这样做吗?它是否准确/可靠?
答案 0 :(得分:1)
如果您仍然需要正则表达式(尽管这不是最佳的),您可以使用以下表达式:
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;
第一部分匹配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