簡體   English   中英

C++ 提升正則表達式日期錯誤

[英]C++ boost regex date error

我對 boost regex 庫很陌生。以下示例代碼用於檢查輸入的日期是否遵循YYYY-MM-DD格式。但是,regex 中似乎存在錯誤。 它總是返回false *

  • 我在 Windows 上運行控制台應用程序。

* 正則表達式取自此處

bool regexValidate(string teststring)
{
boost::regex ex("^(20\\d{2})(\\d{2})(\\d{2})");
if (boost::regex_match(teststring, ex)) {
    cout << "true";
    return true;
}
else {
    return false;
}
}
 int main()
{


string  teststr = "2016-05-15";


cout << teststr << " is ";
if (regexValidate( teststr)) {
    cout << " valid!" << endl;
}
else {
    cout << " invalid!" << endl;
}

system("PAUSE");
return 0;
 }

您快到了; 只需在正則表達式中添加連字符:

"^(20\\d{2})-(\\d{2})-(\\d{2})"

順便說一句,這不會解析 2000 年之前或 2099 年之后的日期。並且最后沒有明確的字符串結尾 ($)。 更像是:

"^(\\d{4})-(\\d{2})-(\\d{2})$"

...我認為應該讓你在最近幾個世紀的任何地方都很好;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM