StringExtension

C# StringExtension

字符串運算

 /// <summary>
        /// 將字符串中的運算符按正常計算 例如按四則運算
        /// </summary>
        /// <param name="expression">標準表達式如 1+15*0.5-200</param>
        /// <returns>返回計算的值,可以爲任意合法的數據類型</returns>
        public static T Calculate<T>(this string expression)
        {
            object retvar = null;
            Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters(
            new string[] { @"System.dll" });
            StringBuilder builder = new StringBuilder("using System;class CalcExp{public static object Calc(){ return \"expression\";}}");
            builder.Replace("\"expression\"", expression);
            string code = builder.ToString();

            System.CodeDom.Compiler.CompilerResults results;
            results = provider.CompileAssemblyFromSource(cp, new string[] { code });
            if (results.Errors.HasErrors)
            {
                retvar = null;
            }
            else
            {
                System.Reflection.Assembly a = results.CompiledAssembly;
                Type t = a.GetType("CalcExp");
                retvar = t.InvokeMember("Calc", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod
                    , System.Type.DefaultBinder, null, null);
            }
            return (T)retvar;
        }

其它見
C#自動計算字符串公式的四種方法

https://blog.csdn.net/cxb2011/article/details/100837168

在這裏插入代碼片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace TS.BLL
{
    public static class StringExtension
    {

        #region 中英文混合左右對齊
        /// <summary>
        /// 中英文混合右對齊方法
        /// </summary>
        /// <param name="str"></param>
        /// <param name="totalByteCount"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string PadLeftEx(this string str, int totalByteCount, char c)
        {
            ASCIIEncoding strData = new ASCIIEncoding();
            int strlen = 0;
            //將字符串轉換爲ASCII編碼的字節數字
            byte[] strBytes = strData.GetBytes(str);
            for (int i = 0; i <= strBytes.Length - 1; i++)
            {
                if (strBytes[i] == 63)  //中文都將編碼爲ASCII編碼63,即"?"號
                {
                    strlen++;
                }

                strlen++;
            }
            return str.PadLeft(totalByteCount - strlen, c);
        }

        /// <summary>
        /// 中英文混合右對齊方法
        /// </summary>
        /// <param name="str"></param>
        /// <param name="totalByteCount"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string PadRightEx(this string str, int totalByteCount, char c)
        {
            ASCIIEncoding strData = new ASCIIEncoding();
            int strlen = 0;
            //將字符串轉換爲ASCII編碼的字節數字
            byte[] strBytes = strData.GetBytes(str);
            for (int i = 0; i <= strBytes.Length - 1; i++)
            {
                if (strBytes[i] == 63)  //中文都將編碼爲ASCII編碼63,即"?"號
                {
                    strlen++;
                }

                strlen++;
            }
            return str.PadRight(totalByteCount - strlen, c);
        }
        #endregion

        #region 獲取中英文混排字符串的實際長度(字節數)
        /// <summary>// 
                /// 獲取中英文混排字符串的實際長度(字節數)
                /// </summary>
                /// <param name="str">要獲取長度的字符串</param>
                /// <returns>字符串的實際長度值(字節數)</returns>
        public static int GetStringLength(this string str)
        {
            if (str.Equals(string.Empty))
            {
                return 0;
            }

            int strlen = 0;
            ASCIIEncoding strData = new ASCIIEncoding();
            //將字符串轉換爲ASCII編碼的字節數字
            byte[] strBytes = strData.GetBytes(str);
            for (int i = 0; i <= strBytes.Length - 1; i++)
            {
                if (strBytes[i] == 63)  //中文都將編碼爲ASCII編碼63,即"?"號
                {
                    strlen++;
                }

                strlen++;
            }
            return strlen;
        }
        #endregion

        #region 字符串轉換爲Pascal格式
        /// <summary>
        /// 字符串轉換爲Pascal格式
        /// </summary>
        /// <param name="s">要轉換的字符串</param>
        /// <returns>返回Pascal格式字符串</returns>
        /// <example>輸入myString,返回MyString這種字符串</example>
        public static string ToPascal(this string p_str)
        {
            return p_str.Substring(0, 1).ToUpper() + p_str.Substring(1);
        }
        #endregion

        #region 字符串轉換爲camel格式
        /// <summary>
        /// 字符串轉換爲camel格式
        /// </summary>
        /// <param name="p_str">要轉換的字符串</param>
        /// <returns></returns>
        public static string ToCamel(this string p_str)
        {
            return p_str.Substring(0, 1).ToLower() + p_str.Substring(1);
        }
        #endregion

        #region 字符串轉換爲數字
        /// <summary>
        /// 字符串轉換爲 Int32格式
        /// </summary>
        /// <param name="p_self"></param>
        /// <returns>int類型字符串,出錯返回int.MinValue</returns>
        public static int ToInt32(this object p_self)
        {
            try
            {
                return Convert.ToInt32(p_self);
            }
            catch
            {
                return int.MinValue;
            }
        }

        public static int ToInt32(this object p_self, int p_defaultValue)
        {
            try
            {
                return Convert.ToInt32(p_self);
            }
            catch
            {
                return p_defaultValue;
            }
        }
        /// <summary>
        /// 字符串轉換爲 Int64格式
        /// </summary>
        /// <param name="p_Self"></param>
        /// <returns>long類型字符串,出錯返回int.MinValue</returns>
        public static long ToInt64(this object p_Self)
        {
            try
            {
                return Convert.ToInt64(p_Self);
            }
            catch
            {
                return int.MinValue;
            }
        }

        public static long ToInt64(this object self, long p_defaultValue)
        {
            try
            {
                return Convert.ToInt64(self);
            }
            catch
            {
                return p_defaultValue;
            }
        }
        #endregion

        #region 轉換成UTF-8字符串
        /// <summary>
        /// 轉換成UTF-8字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String toUtf8String(this string s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                if (c >= 0 && c <= 255)
                {
                    sb.Append(c);
                }
                else
                {
                    byte[] b;
                    try
                    {
                        b = Encoding.UTF8.GetBytes(c.ToString());
                    }
                    catch (Exception)
                    {
                        b = new byte[0];
                    }
                    for (int j = 0; j < b.Length; j++)
                    {
                        int k = b[j];
                        if (k < 0)
                        {
                            k += 256;
                        }

                        sb.Append("%" + Convert.ToString(k, 16).ToUpper());
                    }
                }
            }
            return sb.ToString();
        }
        #endregion

        #region 字符串編碼轉換
        /// <summary>
        /// 字符串編碼轉換
        /// </summary>
        /// <param name="str"></param>
        /// <param name="oldCoding">原編碼</param>
        /// <param name="newEncoding">新編碼</param>
        /// <returns></returns>
        public static string ConvertEnCoding(this string str, Encoding oldCoding, Encoding newEncoding)
        {
            return newEncoding.GetString(oldCoding.GetBytes(str));
        }
        #endregion

        #region IP地址轉換爲祕密的IP地址
        /// <summary>
        /// IP地址轉換爲祕密的IP地址
        /// </summary>
        /// <param name="p_ipAddress">如:202.195.224.100</param>
        /// <returns>返回202.195.224.*類型的字符串</returns>
        public static string ipSecret(this string p_ipAddress)
        {
            string[] ips = p_ipAddress.Split('.');
            StringBuilder sb_screcedIp = new StringBuilder();
            int ipsLength = ips.Length;
            for (int i = 0; i < ipsLength - 1; i++)
            {
                sb_screcedIp.Append(ips[i].ToString() + ".");

            }
            sb_screcedIp.Append("*");
            return sb_screcedIp.ToString();
        }
        #endregion

        #region base64url編碼處理

        public static string ToEnBase64(this string str)
        {
            return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str));
        }

        public static string ToUnBase64(this string str)
        {
            return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(str));
        }

        #endregion

        #region 判斷字符串是否在字符串數組中
        /// <summary>
        /// 判斷字符串是否在字符串數組中
        /// </summary>
        /// <param name="str">要判斷的字符串</param>
        /// <param name="p_targrt">目標數組</param>
        /// <returns></returns>
        public static bool IsInArray(this string str, string[] p_targrt)
        {
            return p_targrt.Contains(str);
            //for (int i = 0; i < targrt.Length; i++)
            //{
            //    if (str == targrt[i])
            //    {
            //        return true;
            //    }
            //}
            //return false;
        }
        #endregion

        #region 字符串數組轉換爲數字數組
        /// <summary>
        /// 字符串數組轉換爲數字數組
        /// </summary>
        /// <param name="p_stringArray"></param>
        /// <returns></returns>
        public static int[] ToIntArray(this string[] p_stringArray)
        {
            int[] returnValue = new int[p_stringArray.Length];
            for (int i = 0; i < p_stringArray.Length; i++)
            {
                returnValue[i] = Convert.ToInt32(p_stringArray[i]);
            }
            return returnValue;

        }
        #endregion

        #region 去除HTML標記
        /// <summary>
        /// 去除HTML標記
        /// </summary>
        /// <param name="p_strHtml">要除去HTML標記的文本</param>
        /// <returns></returns>
        public static string TrimHTML(this string p_strHtml)
        {
            string StrNohtml = p_strHtml;
            StrNohtml = StrNohtml.HtmlDeCode();
            StrNohtml = StrNohtml.TrimScript();
            StrNohtml = Regex.Replace(StrNohtml, "&.{1,6};", "", RegexOptions.IgnoreCase);

            StrNohtml = Regex.Replace(StrNohtml, "<p.*?>", Environment.NewLine, RegexOptions.IgnoreCase);
            StrNohtml = Regex.Replace(StrNohtml, "<br.*?>", Environment.NewLine, RegexOptions.IgnoreCase);

            StrNohtml = Regex.Replace(StrNohtml, "<script[\\w\\W].*?</script>", "", RegexOptions.IgnoreCase);
            StrNohtml = System.Text.RegularExpressions.Regex.Replace(StrNohtml, "<[^>]+>", "");
            StrNohtml = System.Text.RegularExpressions.Regex.Replace(StrNohtml, "&[^;]+;", "");

            return StrNohtml;

        }


        public static string TrimScript(this string str)
        {
            str = Regex.Replace(str, "<script[\\w\\W]*?</script>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "<style[\\w\\W]*?</style>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "<iframe[\\w\\W]*?</iframe>", "", RegexOptions.IgnoreCase);
            return str;
        }
        #endregion

        #region 去除換行符
        /// <summary>
        /// 去除換行符
        /// </summary>
        /// <param name="str">要進行處理的字符串</param>
        /// <returns></returns>
        public static string TrimBR(this string str)
        {
            str = str.Replace("\n", "");
            str = str.Replace("\r", "");
            str = str.Replace("\t", "");
            return str;
        }
        #endregion

        #region 截取文字
        /// <summary>
        /// 截取一段文字.
        /// </summary>
        /// <param name="str">要截取的原文本.</param>
        /// <param name="p_maxLength">截取長度,多少個字</param>
        /// <param name="suffix">The suffix.</param>
        /// <returns></returns>
        public static string Truncate(this string str, int p_maxLength, string suffix = "...")
        {
            // 剩餘的用 ...替換
            var truncatedString = str;

            if (p_maxLength <= 0)
            {
                return truncatedString;
            }

            var strLength = p_maxLength - suffix.Length;

            if (strLength <= 0)
            {
                return truncatedString;
            }

            if (str == null || str.Length <= p_maxLength)
            {
                return truncatedString;
            }

            truncatedString = str.Substring(0, strLength);
            truncatedString = truncatedString.TrimEnd();
            truncatedString += suffix;

            return truncatedString;
        }

        #endregion

        #region 去除XSS攻擊字符
        /// <summary>
        /// 清除字符串中帶有的XSS攻擊威脅的字符
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string CleanForXss(this string input)
        {
            //remove any html
            input = input.StripHtml();
            //strip out any potential chars involved with XSS
            return input.ExceptChars(new HashSet<char>("*?(){}[];:%<>/\\|&'\"".ToCharArray()));
        }

        public static string ExceptChars(this string str, HashSet<char> toExclude)
        {
            var sb = new StringBuilder(str.Length);
            foreach (var c in str.Where(c => toExclude.Contains(c) == false))
            {
                sb.Append(c);
            }
            return sb.ToString();
        }
        #endregion

        #region 去除全部HTML標籤
        /// <summary>
        /// 去除全部HTML標籤
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>返回無任何標籤的字符串</returns>
        public static string StripHtml(this string str)
        {
            const string const_pattern = @"<(.|\n)*?>";
            return Regex.Replace(str, const_pattern, String.Empty);
        }

        #endregion

        #region 刪除字符串尾部的回車/換行/空格
        /// <summary>
        /// 刪除字符串尾部的回車/換行/空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RTrim(this string str)
        {
            for (int i = str.Length; i >= 0; i--)
            {
                if (str[i].Equals(" ") || str[i].Equals("\r") || str[i].Equals("\n"))
                {
                    str.Remove(i, 1);
                }
            }
            return str;
        }
        #endregion

        #region SQL注入敏感字符剔除
        /// <summary>
        /// SQL注入敏感字符剔除
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToSqlEnCode(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }

            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"(\bselect\b.+\bfrom\b)|(\binsert\b.+\binto\b)|(\bdelete\b.+\bfrom\b)|(\bcount\b\(.+\))|(\bdrop\b\s+\btable\b)|(\bupdate\b.+\bset\b)|(\btruncate\b\s+\btable\b)|(\bxp_cmdshell\b)|(\bexec\b)|(\bexecute\b)|(\bnet\b\s+\blocalgroup\b)|(\bnet\b\s+\buser\b)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            str = str.Replace("'", "''");
            str = regex1.Replace(str, ""); //過濾<script></script>標記 
            str = regex2.Replace(str, ""); //過濾href=javascript: (<A>) 屬性 
            str = regex3.Replace(str, " _disibledevent="); //過濾其它控件的on...事件 
            str = regex4.Replace(str, ""); //過濾iframe 
            str = regex5.Replace(str, ""); //過濾frameset
            str = regex6.Replace(str, ""); //過濾frameset
            return str;

        }
        #endregion

        #region 生成以日期時間爲基礎的隨機字符串
        /// <summary>
        /// 生成以日期時間爲基礎的隨機字符串
        /// </summary>
        /// <returns></returns>
        public static string Getfilename()
        {
            Random number = new Random();
            //下面的number.Next(10000,99999).ToString()加入一個5位的在10000到99999之間的隨機數
            //yyyyMMdd代碼年月日。hhmmss代表小時分鐘秒鐘 。fff代表毫秒

            //暫時使用了GUID的那個文件名filenameGUID
            return DateTime.Now.ToString("yyyyMMddhhmmssfff") + "_" + number.Next(10000, 99999).ToString();

        }
        #endregion

        #region 返回GUID唯一標示符
        public static string GetGuid()
        {
            return Guid.NewGuid().ToString();
        }
        #endregion

        #region ///是否是GUID格式
        public static bool ISGUID(this string str)
        {

            return Regex.IsMatch(str, @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");

        }
        #endregion

        #region --剔除腳本注入代碼 已合併到上面的ToSqlEnCode來實現,暫時保留.
        ///// <summary>
        ///// 剔除腳本注入代碼
        ///// </summary>
        ///// <param name="str"></param>
        ///// <returns></returns>
        //public static string TrimDbDangerousChar(this string str)
        //{

        //    return ToSqlEnCode(string str);
        //if (string.IsNullOrEmpty(str))
        // {
        //     return "";
        // }

        //    System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        //    System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        //    System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        //    System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        //    System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        //    str = str.Replace("'", "''");
        //    str = regex1.Replace(str, ""); //過濾<script></script>標記 
        //    str = regex2.Replace(str, ""); //過濾href=javascript: (<A>) 屬性 
        //    str = regex3.Replace(str, " _disibledevent="); //過濾其它控件的on...事件 
        //    str = regex4.Replace(str, ""); //過濾iframe 
        //    str = regex5.Replace(str, ""); //過濾frameset
        //return str;
        // }
        #endregion

        #region  驗證字符串是否爲空字符串
        /// <summary>
        /// 驗證字符串是否爲空字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            if (str == null || str.Length == 0)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 檢測是否有Sql危險字符
        /// <summary>
        /// 檢測是否有Sql危險字符
        /// </summary>
        /// <param name="str">要判斷字符串</param>
        /// <returns>判斷結果</returns>
        public static bool IsSafeSqlString(this string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }
        #endregion

        #region 檢測是否符合郵箱地址規則
        /// <summary>
        /// 檢測是否是郵箱地址格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsanEmailString(this string str)
        {
            return Regex.IsMatch(str, @"^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$");
        }

        #endregion

        #region HtmlDeCode
        public static string HtmlDeCode(this string str)
        {
            //str = RegexReplace(str, "<br[\\s/]{0,2}>", "\r\n");
            //str = RegexReplace(str, "&nbsp;", " ");

            return System.Web.HttpUtility.HtmlDecode(System.Web.HttpUtility.UrlDecode(str)).Replace("''''", "''");
        }

        private static string RegexReplace(string Content, string parrten, string newvalue)
        {
            while (Regex.IsMatch(Content, parrten))
            {
                Content = Regex.Replace(Content, parrten, newvalue, RegexOptions.IgnoreCase);
            }
            return Content;
        }
        #endregion

        #region  UrlDecode
        /// <summary>
        /// UrlDecode
        /// </summary>
        /// <param name="str">要解碼的地址字符串</param>
        /// <returns></returns>
        public static string UrlDecode(this string str)
        {
            return System.Web.HttpUtility.UrlDecode(str);
        }

        public static string UrlDecode(this string str, System.Text.Encoding encode)
        {
            return System.Web.HttpUtility.UrlDecode(str, encode);
        }
        #endregion

        #region  UrlEncode
        /// <summary>
        /// UrlDecode
        /// </summary>
        /// <param name="str">要編碼的地址字符串</param>
        /// <returns></returns>
        public static string UrlEncode(this string str)
        {
            return System.Web.HttpContext.Current.Server.UrlEncode(str);
        }

        public static string UrlEncode(this string str, System.Text.Encoding encode)
        {
            return System.Web.HttpUtility.UrlEncode(str, encode);
        }

        public static string UrlEncode(this string str, string encode)
        {
            return System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.GetEncoding(encode));
        }
        #endregion

        #region 查找字符串出現的次數
        /// <summary>
        /// 查找字符串出現的次數
        /// </summary>
        /// <param name="str">長短文本</param>
        /// <param name="s">單詞</param>
        /// <returns></returns>
        public static int CountString(this string str, string s)
        {
            return Regex.Matches(str, s, RegexOptions.IgnoreCase).Count;
        }
        #endregion

        #region 從HTML中獲取文本,保留br,p,img
        /// <summary>
        /// 從HTML中獲取文本,保留br,p,img
        /// </summary>
        /// <param name="HTML">html代碼</param>
        /// <returns></returns>
        public static string GetTextFromHTML(this string HTML)
        {
            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            return regEx.Replace(HTML, "");
        }
        #endregion

        #region 通過正則表達式在字符串裏面查找子字符串
        /// <summary>
        /// 通過正則表達式在字符串裏面查找子字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="pattern">表達式</param>
        /// <returns></returns>
        public static string FindString(this string str, string pattern)
        {
            Regex reg = new Regex(pattern);
            Match m = reg.Match(str);
            if (m.Groups.Count == 0)
            {
                return "";
            }
            else
            {
                return m.Groups[1].Value;
            }
        }
        #endregion

        #region 獲取字符串中得匹配結果
        /// <summary>
        /// 獲取字符串中得匹配結果
        /// </summary>
        /// <param name="input">源字符串</param>
        /// <param name="pattern">正則表達式</param>
        /// <returns>返回的結果集</returns>
        public static List<string> GetMatch(this string input, string pattern)
        {
            List<string> result = new List<string>();

            Match m = new Regex(pattern, RegexOptions.IgnoreCase).Match(input);
            while (m.Success)
            {
                result.Add(m.Groups["key"].Value);
                m = m.NextMatch();
            }
            return result;
        }
        #endregion

        #region 驗證是否數字
        /// <summary>
        /// 驗證是否數字
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsNumeric(this string str)
        {
            return MachRegex(@"^[-]?\d+[.]?\d*$", str);
        }
        #endregion

        #region  字符串是否爲日期
        /// <summary>
        /// 字符串是否爲日期
        /// </summary>
        /// <param name="s">要進行判斷的字符串</param>
        /// <returns>是日期格式:true 不是:false</returns>
        public static bool IsDateTime(this string s)
        {
            try
            {
                Convert.ToDateTime(s);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 驗證字符串是否是整數
        /// <summary>
        /// 驗證字符串是否是整數
        /// </summary>
        /// <param name="s">要進行驗證的字符串</param>
        /// <returns>整數:true  非整數:false</returns>
        public static bool IsInt(this string s)
        {
            try
            {
                Convert.ToInt32(s);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 驗證URL
        /// <summary>
        /// 驗證URL
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsUrl(this string str)
        {
            return MachRegex(@"^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$", str);
        }
        #endregion

        #region 驗證IP地址
        /// <summary>
        /// 驗證IP地址
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsIpAddress(this string str)
        {
            return MachRegex(@"^(\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])$", str);
        }
        #endregion

        #region 驗證郵編
        /// <summary>
        /// 驗證郵編
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsZipCode(this string str)
        {
            return MachRegex(@"^[0-9]{6}$", str);
        }
        #endregion

        #region 驗證是否漢字
        /// <summary>
        /// 驗證是否漢字
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsChineseChar(this string str)
        {
            return MachRegex(@"^[\u4e00-\u9fa5]{0,}$", str);
        }
        #endregion

        #region 驗證是否Email地址
        /// <summary>
        /// 驗證是否Email地址
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsEmail(this string str)
        {
            return MachRegex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", str);
        }
        #endregion

        #region 驗證是否電話號碼
        /// <summary>
        /// 驗證是否電話號碼
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsTelNumber(this string str)
        {
            return MachRegex(@"^((\d{3,4}-)|\d{3.4}-)?\d{7,8}$", str);
        }
        #endregion

        #region 是否是手機號碼
        /// <summary>
        /// 是否是手機號碼
        /// </summary>
        /// <param name="val"></param>
        public static bool IsMobile(this string val)
        {
            return Regex.IsMatch(val, @"^1[3548]\d{9}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 驗證英文字母
        /// <summary>
        /// 驗證英文字母
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsLatinChar(this string str)
        {
            return MachRegex(@"^[A-Za-z]+$", str);
        }
        #endregion

        #region  身份證有效性驗證
        /// <summary>  
        /// 身份證驗證  
        /// </summary>  
        /// <param name="Id">身份證號</param>  
        /// <returns></returns>  
        public static bool IsIDCard(this string Id)
        {

            if (Id.Length == 18)
            {

                bool check = CheckIDCard18(Id);

                return check;

            }

            else if (Id.Length == 15)
            {

                bool check = CheckIDCard15(Id);

                return check;

            }

            else
            {

                return false;

            }

        }

        /// <summary>  
        /// 18位身份證驗證  
        /// </summary>  
        /// <param name="Id">身份證號</param>  
        /// <returns></returns>  
        private static bool CheckIDCard18(string Id)
        {

            long n = 0;

            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {

                return false;//數字驗證  

            }

            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";

            if (address.IndexOf(Id.Remove(2)) == -1)
            {

                return false;//省份驗證  

            }

            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");

            System.DateTime time = new System.DateTime();

            if (System.DateTime.TryParse(birth, out time) == false)
            {

                return false;//生日驗證  

            }

            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');

            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');

            char[] Ai = Id.Remove(17).ToCharArray();

            int sum = 0;

            for (int i = 0; i < 17; i++)
            {

                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());

            }

            int y = -1;

            Math.DivRem(sum, 11, out y);

            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {

                return false;//校驗碼驗證  

            }

            return true;//符合GB11643-1999標準  

        }

        /// <summary>  
        /// 15位身份證驗證  
        /// </summary>  
        /// <param name="Id">身份證號</param>  
        /// <returns></returns>  
        private static bool CheckIDCard15(string Id)
        {

            long n = 0;

            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {

                return false;//數字驗證  

            }

            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";

            if (address.IndexOf(Id.Remove(2)) == -1)
            {

                return false;//省份驗證  

            }

            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");

            System.DateTime time = new System.DateTime();

            if (System.DateTime.TryParse(birth, out time) == false)
            {

                return false;//生日驗證  

            }

            return true;//符合15位身份證標準  

        }
        #endregion

        #region 驗證用戶密碼。正確格式爲:以字母開頭,長度在6~18之間,只能包含字符、數字和下劃線。
        /// <summary>
        /// 驗證用戶密碼。正確格式爲:以字母開頭,長度在6~18之間,只能包含字符、數字和下劃線。
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsStandardPassword(this string str)
        {
            return MachRegex(@"^[a-zA-Z]\w{5,17}$", str);
        }
        #endregion

        #region 驗證bbs帳號是否符合標準
        /// <summary>
        /// 驗證bbs帳號是否符合標準
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Boolean IsBBSUserName(this String str)
        {
            return MachRegex(@"([_A-Za-z0-9]{6,16})|([\u4E00-\u9FA5_A-Za-z0-9]{3,16})", str);
        }
        #endregion

        #region 對於數據庫是否安全,不包含^%&',;=?$\"等字符
        /// <summary>
        /// 對於數據庫是否安全,不包含^%&',;=?$\"等字符
        /// </summary>
        /// <param name="str">要驗證的字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        public static bool IsSQLSafeChar(this string str)
        {
            return !MachRegex(@"[^%&',;=?$\x22]+", str);
        }
        #endregion

        #region 驗證字符串是否符合正則表達式MachRegex
        /// <summary>
        /// 驗證字符串是否符合正則表達式MachRegex
        /// </summary>
        /// <param name="regex">正則表達式</param>
        /// <param name="str">字符串</param>
        /// <returns>是否符合 true 或者 false</returns>
        private static bool MachRegex(string regex, string str)
        {
            Regex reg = new Regex(regex);
            return reg.IsMatch(str);
        }
        #endregion
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章