本文將介紹一段實(shí)例代碼,來講解利用正則表達(dá)式使C#判斷輸入日期格式是否正確的方法。希望這段代碼能對(duì)大家有所幫助。
通常我們在用C#編寫系統(tǒng)程序或者Web開發(fā)時(shí),都會(huì)遇到需要驗(yàn)證輸入的字符串是否是日期的情況,下面為大家介紹一種非常全面的用正則表達(dá)式驗(yàn)證日期的方法:
c 正則表達(dá)式日期代碼一:
/// summary> /// 是否為日期型字符串 /// /summary> /// param name="StrSource">日期字符串(2008-05-08)/param> /// returns>/returns> public static bool IsDate(string StrSource) { return Regex.IsMatch(StrSource, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$"); } /// summary> /// 是否為時(shí)間型字符串 /// /summary> /// param name="source">時(shí)間字符串(15:00:00)/param> /// returns>/returns> public static bool IsTime(string StrSource) { return Regex.IsMatch(StrSource, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$"); } /// summary> /// 是否為日期+時(shí)間型字符串 /// /summary> /// param name="source">/param> /// returns>/returns> public static bool IsDateTime(string StrSource) { return Regex.IsMatch(StrSource, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$ "); }
c 正則表達(dá)式日期代碼二:
//是否是整數(shù) public static bool IsInt(string StrSource) { return Regex.IsMatch(StrSource, @"^[0-9]*$"); } public static bool IsDate(string strDate) { if (string.IsNullOrEmpty(strDate)) return false; string s_reg = @"^(?ni:(?=\\d)((?'year'((1[6-9])|([2-9]\\d))\\d\\d)(?'sep'[/.-])(?'month'0?[1-9]|1[012])\\2 (?'day'((?!(\\2((0?[2469])|11)\\2))31)|(?!\\2(0?2)\\2)(29|30)|((?=((1[6-9]|[2-9]\\d)(0[48]| [2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00)\\2\\3\\2)29)|((0?[1-9])|(1\\d)|(2[0- 8])))(?:(?=\\x20\\d)\\x20|$))?((?time>((0?[1-9]|1[012])(:[0-5]?\\d){0,2}(\\x20[AP]M))|([01]? \\d|2[0-3])(:[0-5]?\\d){1,2}))?)$"; Regex reg = new Regex(s_reg); if (reg.IsMatch(strDate.ToLower())) return true; else return false; }
以上就是小編給大家介紹的C#正則表達(dá)式判斷輸入日期格式是否正確的全部內(nèi)容,希望對(duì)大家學(xué)習(xí)c正則表達(dá)式日期判斷有所幫助。同時(shí)也非常感謝大家一直以來對(duì)腳本之家網(wǎng)站的支持。
標(biāo)簽:六安 三亞 梅州 綿陽 池州 鞍山 咸陽 恩施
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《C#正則表達(dá)式判斷輸入日期格式是否正確》,本文關(guān)鍵詞 正則,表達(dá)式,判斷,輸入,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。