本文實例講述了C#常用正則驗證函數。分享給大家供大家參考,具體如下:
1、Ip地址驗證
/// <summary>/// Ip地址驗證/// </summary>public static bool CheckIp(string ip){ bool result = false; Regex ipReg = new Regex(@"^(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])/.(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])/.(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])/.(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])$"); if (ipReg.IsMatch(ip)) { result = true; } return result;}
2、價格驗證
/// <summary>/// 價格驗證/// </summary>/// <param name="priceStr"></param>/// <returns></returns>public bool CheckPrice(string priceStr){ bool result = false; Regex regex = new Regex(@"^/d+(/./d{1,2})?$", RegexOptions.IgnoreCase); Match match = regex.Match(priceStr); if (match.Success) { result = true; } return result;}
3、正整數驗證
/// <summary>/// 正整數驗證/// </summary>public static bool CheckPositiveInteger(string numStr){ bool result = false; Regex regex = new Regex(@"^[1-9]/d*$", RegexOptions.IgnoreCase); Match match = regex.Match(numStr); if (match.Success) { result = true; } return result;}
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.VeVB.COm/regex/javascript
正則表達式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
更多關于C#相關內容感興趣的讀者可查看本站專題:《C#正則表達式用法總結》、《C#編碼操作技巧總結》、《C#中XML文件操作技巧匯總》、《C#數據結構與算法教程》、《C#面向對象程序設計入門教程》及《C#程序設計之線程使用技巧總結》
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答