using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace Common { /// ///字符串拓展 /// public static class StringExtension { /// /// 隐藏中间字符串 /// /// /// public static string GetHideCentre(this string str) { if (str.Length > 8) { return string.Format("{0}***{1}", str.Substring(0, 4), str.Substring(str.Length - 4, 4)); } else if (str.Length > 5) { return string.Format("{0}***{1}", str.Substring(0, 2), str.Substring(str.Length - 2, 2)); } else if (str.Length > 4) { return string.Format("{0}***{1}", str.Substring(0, 1), str.Substring(str.Length - 1, 1)); } else { return GetHideHead(str); } } /// /// 隐藏头部 /// /// /// public static string GetHideHead(this string str) { var length = 1; length = length > str.Length ? str.Length : length; if (str.Length < 4) { length = 1; if (str.Length == 1) { return str; } return "**" + str.Substring(str.Length - length, length); } length = 4; return "****" + str.Substring(str.Length - length, length); } /// /// 根据正则表达式返回符合条件的字符串 /// /// /// public static string GetRegex(this string str, string Pattern) { var vallist = str.GetRegexList(Pattern); return vallist.Count > 0 ? vallist[0] : ""; } /// /// 根据正则表达式返回符合条件的字符串list /// /// /// 正则表达式 /// 字符串分隔符队列默认 , 回车 /// public static List GetRegexList(this string str, string pattern, List Splitstr =null) { var list = new List(); if (str == null) { return list; } List _Splitstr =new List { ',','\n',' ' }; if (Splitstr == null) { Splitstr = _Splitstr; } else { Splitstr.AddRange(_Splitstr); } try { var strlist = new List(); foreach (var spli in Splitstr) { strlist.AddRange(str.Split(spli).ToList()); } strlist.ForEach(item => { foreach (var match in Regex.Matches(item, pattern)) { var val = match.ToString(); if (list.IndexOf(val) < 0) { list.Add(val); } } }); } catch { } return list; } /// /// 移除所有空格包含中间的。 /// /// /// public static string TrimAll(this string str) { var val= str.Trim().Replace(" ","").Replace(" ",""); return val; } /// /// 用于判断是否为空字符 /// /// /// public static bool IsNull(this string s) { return s == null || (s.Trim().Length == 0); } /// /// 判断是否是guid /// /// /// public static bool IsGuid(this string s) { return Guid.TryParse(s,out var newgid); } /// /// 用于判断是否为非空字符 /// /// /// public static bool IsNotNull(this string s) { return !s.IsNull(); } #region 加密算法 /// /// 将字符串SHA1 /// /// /// public static string ToSHA1(this string str) { return SafeTools.SHA1(str).ToLower(); } /// /// 将字符串转换成MD5加密字符串 /// /// /// public static string ToMd5(this string orgStr) { using (var md5 = MD5.Create()) { var encoding = Encoding.UTF8; var encryptedBytes = md5.ComputeHash(encoding.GetBytes(orgStr)); var sb = new StringBuilder(32); foreach (var bt in encryptedBytes) { sb.Append(bt.ToString("x").PadLeft(2, '0')); } return sb.ToString().ToLower(); } } #endregion /// /// 获取扩展名 /// /// /// public static string GetExt(this string s) { var ret = string.Empty; if (!s.Contains('.')) return ret; var temp = s.Split('.'); ret = temp[temp.Length - 1]; return ret; } /// /// 验证QQ格式 /// /// /// public static bool IsQq(this string s) { return s.IsNull() || Regex.IsMatch(s, @"^[1-9]\d{4,15}$"); } /// /// 将字符串根据分隔符转换我List /// /// /// 分隔符 /// public static List ToListString(this string str, char split) { return new List(str.Split(split)); } /// /// 判断是否为有效的Email地址 /// /// /// public static bool IsEmail(this string s) { if (!s.IsNull()) { //return Regex.IsMatch(s, // @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + // @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"); const string pattern = @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"; return Regex.IsMatch(s, pattern); } return false; } /// /// 判断是否是url /// /// /// public static bool IsUrl(this string s) { if (!s.IsNull()) { const string pattern = @"^(http://|https://)?((?:[A-Za-z0-9]+-[A-Za-z0-9]+|[A-Za-z0-9]+)\.)+([A-Za-z]+)[/\?\:]?.*$"; return Regex.IsMatch(s,pattern); } return false; } /// /// 验证是否是合法的电话号码 /// /// /// public static bool IsPhone(this string s) { if (!s.IsNull()) { return Regex.IsMatch(s, @"^\+?((\d{2,4}(-)?)|(\(\d{2,4}\)))*(\d{0,16})*$"); } return true; } /// /// 验证是否是合法的手机号码 /// /// /// public static bool IsMobile(this string s) { if (!s.IsNull()) { return Regex.IsMatch(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"); } return false; } /// /// 验证是否是合法的邮编 /// /// /// public static bool IsZipCode(this string s) { if (!s.IsNull()) { return Regex.IsMatch(s, @"[1-9]\d{5}(?!\d)"); } return true; } /// /// 验证是否是合法的传真 /// /// /// public static bool IsFax(this string s) { if (!s.IsNull()) { return Regex.IsMatch(s, @"(^[0-9]{3,4}\-[0-9]{7,8}$)|(^[0-9]{7,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)"); } return true; } /// /// 检查字符串是否为有效的int数字 /// /// /// public static bool Isint(this string val) { if (IsNull(val)) return false; int k; return int.TryParse(val, out k); } /// /// 检查字符串是否为有效的long数字 /// /// /// public static bool Islong(this string val) { if (IsNull(val)) return false; long k; return long.TryParse(val, out k); } /// /// 字符串转数字,未转换成功返回0 /// /// /// public static int ToInt(this string val) { if (IsNull(val)) return 0; int k; return int.TryParse(val, out k) ? k : 0; } /// /// 字符串转 浮点Double /// /// /// public static double ToDouble(this string val) { if (IsNull(val)) { return 0; } double values; return double.TryParse(val, out values) ? values : 0; } /// /// 将int间隔字符串转换为list /// /// /// /// public static List ToIntList(this string str, char Split=',') { return str.Split(Split).strToIntArray().ToList(); } /// /// 判断是否是json字符串 /// /// /// public static bool IsJson(this string str) { try { System.Text.Json.JsonSerializer.Deserialize(str); return true; } catch { return false; } } /// /// 检查字符串是否为有效的INT64数字 /// /// /// public static bool IsInt64(this string val) { if (IsNull(val)) return false; long k; return long.TryParse(val, out k); } /// /// 验证是否是身份证 /// /// /// public static bool IsCardId(this string ID) { var r = false; if (IsNull(ID)) r= false; if (ID.Length == 15) { var date = $"19{ID.Substring(6, 2)}-{ID.Substring(8, 2)}-{ID.Substring(10, 2)}"; DateTime dt; return DateTime.TryParse(date,out dt); } else if (ID.Length == 18) { var date = $"{ID.Substring(6, 4)}-{ID.Substring(10, 2)}-{ID.Substring(12, 2)}"; DateTime dt; return DateTime.TryParse(date, out dt); } else { r= false; } return r; } /// /// 检查字符串是否为有效的double /// /// /// public static bool IsDecimal(this string val) { if (IsNull(val)) return false; double d; return double.TryParse(val, out d); } /// ///检测字符串是否是时间类型 /// /// /// public static bool IsDateTime(this string val) { if (IsNull(val)) return false; DateTime d; return DateTime.TryParse(val,out d); } /// /// 将时间字符串转为指定格式的字符串 自动判断是否是时间格式,如果不是时间格式则返回原有字符串 /// /// /// /// public static string GetDateTimeFormat(this string val,string Format= "yyyy-MM-dd") { if (Format.IsNull()) { Format = "yyyy-MM-dd"; } return val.IsDateTime() ? ((DateTime)val.ToDateTime()).ToString(Format) : val; } /// /// 获取字符串内包换的数字行字符串 /// /// /// 为空的时候返回的默认字符串 /// public static string GetIncludeNumber(this string val,string defaultstr="0") { if (val.IsNull()) { return defaultstr; } var str = val.GetRegex("[0-9]{1,100}"); if (str.IsNull()) { str = defaultstr; } return str; } /// /// 字符串转时间 非时间返回空 /// /// /// public static DateTime? ToDateTime(this string val) { if (val.IsDateTime()) { return DateTime.Parse(val); } else { return null; } } /// /// 将时间类型字符转时间戳 入股不是时间类型则返回0 /// /// /// public static long ToTimestamp(this string Val) { var time = Val.ToDateTime(); return time != null ? ((DateTime)time).ToTimeStamp() : 0; } /// /// 从左边截取N个字符 /// /// /// public static string GetLeftStr(this string val,int count=0) { if (count > val.Length) return null; return val.Substring(0,count); } /// /// 获取一个字符串在另外一个字符串出现的次数 /// /// public static int GetincludeCount(this string str,string indexstr) { var val = str.Replace(indexstr,null); return (str.Length - val.Length) / indexstr.Length; } /// ///从右边截取N个字符 /// /// /// /// public static string GetRightStr(this string val, int count=0) { if (count > val.Length) return null; return val.Substring(val.Length-count, count); } /// /// 索引字符串是否以指定列表中的字符串开头 /// /// /// /// public static bool IndexStartWithList(this string val, List List) { var r = false; foreach (var item in List) { if (val.StartsWith(item)) { r=true; break; } } return r; } /// /// 将Base64 解析解出 如果失败则返回null /// /// /// public static string Base64ToString(this string val) { string r = null; try { r = Encoding.UTF8.GetString(Convert.FromBase64String(val)); } catch { } return r; } /// /// 判断是否是Base64 /// /// /// public static bool IsBase64(this string val) { bool r = false; try { var getr= Encoding.UTF8.GetString(Convert.FromBase64String(val)); r = true; } catch { r = false; } return r; } /// /// 字符转换为base64 错误或空字符串返回 null /// /// /// public static string ToBase64(this string val) { string str = null; if (val.IsNull()) return null; try { str = Convert.ToBase64String(Encoding.UTF8.GetBytes(val)); } catch { str = null; } return str; } /// /// 获取字符串中的数字字符串 /// /// public static string GetIntStr(this string val) { var r = ""; var clist = new List() {'0','1','2','3','4','5','6','7','8','9' }; foreach (var v in val) { if (clist.IndexOf(v) >= 0) { r+=v; } } return r; } public static bool _windows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); /// /// 自动调整windows/linux下面文件目录斜杠的处理 /// /// /// public static string ReplacePath(this string path) { if (string.IsNullOrEmpty(path)) return ""; if (_windows) return path.Replace("/", "\\"); return path.Replace("\\", "/"); } public static bool IsInt(this object obj) { if (obj == null) return false; bool reslut = Int32.TryParse(obj.ToString(), out int _number); return reslut; } public static bool IsDate(this object str) { return IsDate(str, out _); } public static bool IsDate(this object str, out DateTime dateTime) { dateTime = DateTimeExtension.GetUtcDateTime(); if (str == null || str.ToString() == "") { return false; } return DateTime.TryParse(str.ToString(), out dateTime); } /**/ /// /// 判断一个字符串是否为合法数字(指定整数位数和小数位数) /// /// 字符串 /// 整数位数 /// 小数位数 /// public static bool IsNumber(this string str, int precision, int scale) { if ((precision == 0) && (scale == 0)) { return false; } string pattern = @"(^\d{1," + precision + "}"; if (scale > 0) { pattern += @"\.\d{0," + scale + "}$)|" + pattern; } pattern += "$)"; return Regex.IsMatch(str, pattern); } /// /// 根据传入格式判断是否为小数 /// /// /// 18,5 /// public static bool IsNumber(this string str, string formatString) { if (string.IsNullOrEmpty(str)) return false; int precision = 32; int scale = 5; try { if (string.IsNullOrEmpty(formatString)) { precision = 10; scale = 2; } else { string[] numbers = formatString.Split(','); precision = Convert.ToInt32(numbers[0]); scale = numbers.Length == 0 ? 2 : Convert.ToInt32(numbers[1]); } } catch { }; return IsNumber(str, precision, scale); } public static bool IsNullOrEmpty(this object str) { if (str == null) return true; return str.ToString() == ""; } public static int GetInt(this object obj) { if (obj == null) return 0; int.TryParse(obj.ToString(), out int _number); return _number; } /// /// 获取 object 中的枚举值 /// /// /// /// public static long GetLong(this object obj) { if (obj == null) return 0; try { return Convert.ToInt64(Convert.ToDouble(obj)); } catch { return 0; } } /// /// 获取 object 中的 float /// /// /// public static float GetFloat(this object obj) { if (System.DBNull.Value.Equals(obj) || null == obj) return 0; try { return float.Parse(obj.ToString()); } catch { return 0; } } public static double GetDouble(this object obj) { if (System.DBNull.Value.Equals(obj) || null == obj) return 0; try { return Convert.ToDouble(obj); } catch { return 0; } } /// /// 获取 object 中的 decimal /// /// /// /// public static decimal GetDecimal(this object obj) { if (System.DBNull.Value.Equals(obj) || null == obj) return 0; try { return Convert.ToDecimal(obj); } catch { return 0; } } /// /// 获取 object 中的 decimal /// /// /// /// public static DateTime? GetDateTime(this object obj) { if (System.DBNull.Value.Equals(obj) || null == obj) return null; bool result = DateTime.TryParse(obj.ToString(), out DateTime dateTime); if (!result) return null; return dateTime; } public static object ParseTo(this string str, string type) { switch (type) { case "System.Boolean": return ToBoolean(str); case "System.SByte": return ToSByte(str); case "System.Byte": return ToByte(str); case "System.UInt16": return ToUInt16(str); case "System.Int16": return ToInt16(str); case "System.uInt32": return ToUInt32(str); case "System.Int32": return ToInt32(str); case "System.UInt64": return ToUInt64(str); case "System.Int64": return ToInt64(str); case "System.Single": return ToSingle(str); case "System.Double": return ToDouble(str); case "System.Decimal": return ToDecimal(str); case "System.DateTime": return ToDateTime(str); case "System.Guid": return ToGuid(str); } throw new NotSupportedException(string.Format("The string of \"{0}\" can not be parsed to {1}", str, type)); } public static sbyte? ToSByte(this string value) { sbyte value2; if (sbyte.TryParse(value, out value2)) { return value2; } return null; } public static byte? ToByte(this string value) { byte value2; if (byte.TryParse(value, out value2)) { return value2; } return null; } public static ushort? ToUInt16(this string value) { ushort value2; if (ushort.TryParse(value, out value2)) { return value2; } return null; } public static short? ToInt16(this string value) { if (short.TryParse(value, out short value2)) { return value2; } return null; } public static uint? ToUInt32(this string value) { uint value2; if (uint.TryParse(value, out value2)) { return value2; } return null; } public static ulong? ToUInt64(this string value) { ulong value2; if (ulong.TryParse(value, out value2)) { return value2; } return null; } public static long? ToInt64(this string value) { long value2; if (long.TryParse(value, out value2)) { return value2; } return null; } public static float? ToSingle(this string value) { float value2; if (float.TryParse(value, out value2)) { return value2; } return null; } public static decimal? ToDecimal(this string value) { decimal value2; if (decimal.TryParse(value, out value2)) { return value2; } return null; } public static bool? ToBoolean(this string value) { bool value2; if (bool.TryParse(value, out value2)) { return value2; } return null; } public static Guid? ToGuid(this string str) { Guid value; if (Guid.TryParse(str, out value)) { return value; } return null; } public static int? ToInt32(this string input) { if (string.IsNullOrEmpty(input)) { return null; } int value; if (int.TryParse(input, out value)) { return value; } return null; } /// /// 将字符串分隔成list /// /// /// /// public static List StringToList(string value, string strSplit) { List lst = new List(); if (string.IsNullOrEmpty(value)) return lst; else if (value.IndexOf(strSplit) == -1) return new List() { value }; lst = new List(value.Split(new string[] { strSplit }, StringSplitOptions.RemoveEmptyEntries)); return lst; } /// /// 替换空格字符 /// /// /// 替换为该字符 /// 替换后的字符串 public static string ReplaceWhitespace(this string input, string replacement = "") { return string.IsNullOrEmpty(input) ? null : Regex.Replace(input, "\\s", replacement, RegexOptions.Compiled); } private static char[] randomConstant ={ '0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' }; /// /// 生成指定长度的随机数 /// /// /// public static string GenerateRandomNumber(this int length) { System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62); Random rd = new Random(); for (int i = 0; i < length; i++) { newRandom.Append(randomConstant[rd.Next(62)]); } return newRandom.ToString(); } public static string MaxSubstring(this string origin, int maxLength) { return origin.Length >= maxLength ? origin.Substring(0, maxLength) : origin; } public static string SafeTrim(this string s) { if (string.IsNullOrEmpty(s)) { //return string.Empty; return null; } return s.Trim(); } /// /// 超过长度自动加省略号 /// /// /// 字节数 /// 是否双字节 /// public static string Ellipsis(this string source, int num, bool isDoubleByte = true) { if (isDoubleByte) { num = 2 * num; } if (string.IsNullOrWhiteSpace(source)) { return string.Empty; } int len = Encoding.Default.GetBytes(source).Length; if (len <= num) { return source; } int curNum = 0; int curLen = 0; foreach (var item in source) { curNum += Encoding.Default.GetBytes(item.ToString()).Length; if (curNum > num) { break; } curLen++; } return source.Substring(0, curLen) + "..."; } public static string TrimAllEmpty(this string source) { if (string.IsNullOrWhiteSpace(source)) { return string.Empty; } Regex replaceSpace = new Regex(@"\s{1,}", RegexOptions.IgnoreCase); return replaceSpace.Replace(source, string.Empty).Trim(); } public static string GetNeedString(this string s, string reg) { Regex r = new Regex(@reg, RegexOptions.IgnoreCase); return r.Replace(s, string.Empty); } /// /// 去除SQL特殊字符 /// /// /// public static string ReplaceSQLChar(this string str) { if (string.IsNullOrEmpty(str)) return String.Empty; str = str.Replace("'", ""); str = str.Replace(";", ""); str = str.Replace(",", ""); str = str.Replace("?", ""); str = str.Replace("<", ""); str = str.Replace(">", ""); str = str.Replace("(", ""); str = str.Replace(")", ""); str = str.Replace("@", ""); str = str.Replace("=", ""); str = str.Replace("+", ""); str = str.Replace("*", ""); str = str.Replace("&", ""); str = str.Replace("#", ""); str = str.Replace("%", ""); str = str.Replace("$", ""); //删除与数据库相关的词 str = Regex.Replace(str, "select", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "insert", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "delete from", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "count", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "drop table", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "asc", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "mid", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "char", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "xp_cmdshell", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "exec master", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "net localgroup administrators", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "and", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "net user", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "or", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "net", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "--", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "delete", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "drop", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "script", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "update", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "and", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "chr", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "master", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "declare", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "mid", "", RegexOptions.IgnoreCase); return str; } } }