這是我在開發了這幾年的時間中,總結出來一些知識點,我的感受一邊開發一邊總結真的是一個很是好的習慣,特別有助於我的技術的提升……正則表達式
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI.HtmlControls; using System.Web.UI; using System.Text.RegularExpressions; namespace Common { public class Validate { private static readonly Regex RegPhone = new Regex("(^(\\d{11})$|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)"); //電話號碼和手機驗證 private static Regex RegEmail = new Regex("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@([\\w-]+\\.)+\\w{2,3})\\s*$"); //w 英文字母或數字的字符串,和 [a-zA-Z0-9] 語法同樣 private static Regex RegNum = new Regex("^[0-9]+$"); //必須是數字正則表達式(小數或整數) private static Regex regex = new Regex(@"/^[0-9]+\.?[0-9]{0,3}$/"); /// <summary> /// 身份證正值表達式 /// </summary> private static readonly Regex RegCardId = new Regex("(^\\d{15}$)|(^\\d{17}([0-9]|X|x)$)"); #region 肯定用戶輸入是否合法 /// <summary> /// 肯定用戶輸入是否合法 /// </summary> /// <param name="text">用戶輸入字符串</param> /// <param name="maxLength">最大字符串長度</param> /// <returns></returns> public static string InputText(string text, int maxLength) { if (string.IsNullOrEmpty(text)) return string.Empty; text = text.Trim(); if (maxLength != 0) if (text.Length > maxLength) text = text.Substring(0, maxLength); text = Regex.Replace(text, "[\\s]{2,}", " "); text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //屏蔽標籤 text = text.Replace("'", "''"); return text; } #endregion #region 驗證電話號碼 // 電話號碼和手機號碼檢查 /// <summary> /// 電話號碼和手機號碼檢查 /// </summary> /// <param name="inputData">電話號碼或手機號碼</param> /// <returns>匹配結果</returns> public static bool IsPhone(string inputData) { Match m = RegPhone.Match(inputData); return m.Success; } #endregion #region 驗證參數是否爲中文字符 /// <summary> /// 驗證參數是否爲中文字符 /// </summary> /// <param name="input">輸入參數</param> /// <returns></returns> public static bool IsChinese(string input) { Regex regex = new Regex(@"[\u4e00-\u9fa5]", RegexOptions.IgnoreCase); return regex.IsMatch(input); } #endregion #region 郵件地址 /// <summary> /// 郵件地址驗證 /// </summary> /// <param name="inputData">輸入字符串</param> /// <returns>驗證結果</returns> public static bool IsEmail(string inputData) { Match m = RegEmail.Match(inputData); return m.Success; } #endregion #region 是否爲數字 /// <summary> /// 是否爲數字 /// </summary> /// <param name="inputData">輸入字符串</param> /// <returns>是否爲數字</returns> public static bool IsNum(string inputData) { if(string.IsNullOrEmpty(inputData)) { return false; } Match m = RegNum.Match(inputData); return m.Success; } /// <summary> /// 判斷是不是整數或小數 /// </summary> /// <param name="str">輸入的字符串</param> /// <returns>是否爲數字</returns> public static bool IsNumAll(string str) { if (string.IsNullOrEmpty(str)) { return false; } Match m = regex.Match(str); return m.Success; } #endregion #region 是否爲身份證 /// <summary> /// 是否爲身份證 /// </summary> /// <param name="inputData">輸入字符串</param> /// <returns>是否爲身份證</returns> public static bool IsCardId(string inputData) { Match m = RegCardId.Match(inputData); return m.Success; } #endregion /// <summary> /// 判斷字符串是不是純數字 /// </summary> /// <param name="message">源字符串</param> /// <returns></returns> public static bool IsNumberic(string message)//, out int result { System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$"); var result = -1; if (rex.IsMatch(message)) { result = int.Parse(message); return true; } else return false; } /// <summary> /// 截取字符串 /// </summary> /// <param name="number">截取多少位</param> /// <param name="str">原字符串</param> /// <returns></returns> public static string InterceptionBytes(int number, string str) { //4*6 24 -2 22*2=44 44ge 字節 43 if (str == null) return ""; var result = new StringBuilder(); var count = 0; if (Encoding.GetEncoding("GB2312").GetByteCount(str) <= number) { return str; } foreach (char t in str) { if (Encoding.GetEncoding("GB2312").GetByteCount(new[] { t }) == 2) { count += 2; result.Append(t); } else if (Encoding.GetEncoding("GB2312").GetByteCount(new[] { t }) == 1) { count += 1; result.Append(t); } else { count += 3; result.Append(t); } if (count >= (number - 2)) break; } result.Append("..."); return result.ToString(); } /// <summary> /// 返回指定位數的隨機密碼(數字和字母的組合) /// </summary> /// <param name="median">密碼位數(非負數)</param> /// <returns>string</returns> public static string GetPassword(int median) { Random ra = new Random(); string str = ""; string newstr = ""; int l1 = median / 3; int l2 = median / 3; int l3 = median / 3 + median % 3; int[] lower = new int[l1];//小寫字母 int[] upper = new int[l2];//大寫字母 int[] num = new int[l3]; //數字 byte[] bs1 = new byte[l1]; //存放小寫字母 byte[] bs2 = new byte[l2]; //存放大寫字母 Encoding en = Encoding.Default; #region //初始化隨機數和字母 for (int i = 0; i < lower.Length; i++) { lower[i] = ra.Next(65, 91); bs1[i] = byte.Parse(lower[i].ToString()); } for (int j = 0; j < upper.Length; j++) { upper[j] = ra.Next(97, 123); bs2[j] = byte.Parse(upper[j].ToString()); } for (int k = 0; k < num.Length; k++) { num[k] = ra.Next(0, 10); } #endregion string tempnum = num.Aggregate("", (current, t) => current + t); //拼接成臨時字符串,方便按照下標取值 str += en.GetString(bs1) + en.GetString(bs2) + tempnum; List<string> li = new List<string>(); for (int a = 0; a < str.Length; a++) { li.Insert(a, str[a].ToString()); } while (li.Count != 0) { var count = ra.Next(0, li.Count); newstr += li[count]; li.RemoveAt(count); } return newstr; } /// <summary> /// 加密處理 /// </summary> /// <param name="Input"></param> /// <returns></returns> public static string Encrypt(string Input) { try { var des = new DESCryptoServiceProvider(); var inputByteArray = Encoding.UTF8.GetBytes(Input); var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateEncryptor(Key, Iv), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception) { return ""; } } /// <summary> /// 解密處理 /// </summary> /// <param name="Input"></param> /// <returns></returns> public static string Decrypt(string Input) { if (!string.IsNullOrEmpty(Input)) { Input = Input.Replace(" ", "+"); try { var des = new DESCryptoServiceProvider(); var inputByteArray = Convert.FromBase64String(Input); var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateDecryptor(Key, Iv), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); var encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception) { return ""; } } return ""; } #region 全角半角轉換 /// <summary> /// 轉全角的函數(SBC case) /// </summary> /// <param name="input">任意字符串</param> /// <returns>全角字符串</returns> ///<remarks> ///全角空格爲12288,半角空格爲32 ///其餘字符半角(33-126)與全角(65281-65374)的對應關係是:均相差65248 ///</remarks> public static string ToSBC(string input) { //半角轉全角: char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 32) { c[i] = (char)12288; continue; } if (c[i] < 127) c[i] = (char)(c[i] + 65248); } return new string(c); } /// <summary> 轉半角的函數(DBC case) </summary> /// <param name="input">任意字符串</param> /// <returns>半角字符串</returns> ///<remarks> ///全角空格爲12288,半角空格爲32 ///其餘字符半角(33-126)與全角(65281-65374)的對應關係是:均相差65248 ///</remarks> public static string ToDBC(string input) { char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 12288) { c[i] = (char)32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char)(c[i] - 65248); } return new string(c); } #endregion /// <summary> /// 返回全路徑文件名稱 /// </summary> /// <param name="folderPath"></param> /// <param name="fileName"></param> /// <returns></returns> public static string GetValidateFileName(string folderPath, string fileName) { string result = string.Empty; DirectoryInfo di = new DirectoryInfo(folderPath); FileInfo[] files = di.GetFiles(fileName); if (files.Any()) { result = files[0].FullName; } return result; } #region 獲取時間戳 /// <summary> /// 獲取時間戳 /// </summary> /// <returns></returns> public static string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } #endregion ///獲取隨機數 public static int RandomInteger(int min, int max) { RNGCryptoServiceProvider Rand = new RNGCryptoServiceProvider(); uint scale = uint.MaxValue; while (scale == uint.MaxValue) { // Get four random bytes. byte[] four_bytes = new byte[4]; Rand.GetBytes(four_bytes); // Convert that into an uint. scale = BitConverter.ToUInt32(four_bytes, 0); } // Add min to the scaled difference between max and min. return (int)(min + (max - min) * (scale / (double)uint.MaxValue)); } } }