国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#字符串的常用操作工具類代碼分享

2020-01-24 02:41:49
字體:
供稿:網(wǎng)友

實現(xiàn)以下功能:

驗證字符串是否由正負號(+-)、數(shù)字、小數(shù)點構(gòu)成,并且最多只有一個小數(shù)點
驗證字符串是否僅由[0-9]構(gòu)成
驗證字符串是否由字母和數(shù)字構(gòu)成
驗證是否為空字符串。若無需裁切兩端空格,建議直接使用 String.IsNullOrEmpty(string)
裁切字符串(中文按照兩個字符計算)
裁切字符串(中文按照兩個字符計算,裁切前會先過濾 Html 標(biāo)簽)
過濾HTML標(biāo)簽
獲取字符串長度。與string.Length不同的是,該方法將中文作 2 個字符計算。
將形如 10.1MB 格式對用戶友好的文件大小字符串還原成真實的文件大小,單位為字節(jié)。
根據(jù)文件夾命名規(guī)則驗證字符串是否符合文件夾格式
根據(jù)文件名命名規(guī)則驗證字符串是否符合文件名格式
驗證是否為合法的RGB顏色字符串

C#代碼:

復(fù)制代碼 代碼如下:

public static class ExtendedString
{
    /// <summary>
    /// 驗證字符串是否由正負號(+-)、數(shù)字、小數(shù)點構(gòu)成,并且最多只有一個小數(shù)點
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumeric(this string str)
    {
        Regex regex = new Regex(@"^[+-]?/d+[.]?/d*$");
        return regex.IsMatch(str);           
    }

    /// <summary>
    /// 驗證字符串是否僅由[0-9]構(gòu)成
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumericOnly(this string str)
    {
        Regex regex = new Regex("[0-9]");
        return regex.IsMatch(str);
    }

    /// <summary>
    /// 驗證字符串是否由字母和數(shù)字構(gòu)成
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumericOrLetters(this string str)
    {
        Regex regex = new Regex("[a-zA-Z0-9]");
        return regex.IsMatch(str);
    }

    /// <summary>
    /// 驗證是否為空字符串。若無需裁切兩端空格,建議直接使用 String.IsNullOrEmpty(string)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    /// <remarks>
    /// 不同于String.IsNullOrEmpty(string),此方法會增加一步Trim操作。如 IsNullOrEmptyStr(" ") 將返回 true。
    /// </remarks>
    public static bool IsNullOrEmptyStr(this string str)
    {
        if (string.IsNullOrEmpty(str)) { return true; }
        if (str.Trim().Length == 0) { return true; }
        return false;
    }

    /// <summary>
    /// 裁切字符串(中文按照兩個字符計算)
    /// </summary>
    /// <param name="str">舊字符串</param>
    /// <param name="len">新字符串長度</param>
    /// <param name="HtmlEnable">為 false 時過濾 Html 標(biāo)簽后再進行裁切,反之則保留 Html 標(biāo)簽。</param>
    /// <remarks>
    /// <para>注意:<ol>
    /// <li>若字符串被截斷則會在末尾追加“...”,反之則直接返回原始字符串。</li>
    /// <li>參數(shù) <paramref name="HtmlEnable"/> 為 false 時會先調(diào)用<see cref="uoLib.Common.Functions.HtmlFilter"/>過濾掉 Html 標(biāo)簽再進行裁切。</li>
    /// <li>中文按照兩個字符計算。若指定長度位置恰好只獲取半個中文字符,則會將其補全,如下面的例子:<br/>
    /// <code><![CDATA[
    /// string str = "感謝使用uoLib。";
    /// string A = CutStr(str,4);   // A = "感謝..."
    /// string B = CutStr(str,5);   // B = "感謝使..."
    /// ]]></code></li>
    /// </ol>
    /// </para>
    /// </remarks>
    public static string CutStr(this string str, int len, bool HtmlEnable)
    {
        if (str == null || str.Length == 0 || len <= 0) { return string.Empty; }

        if (HtmlEnable == false) str = HtmlFilter(str);
        int l = str.Length;

        #region 計算長度
        int clen = 0;//當(dāng)前長度
        while (clen < len && clen < l)
        {
            //每遇到一個中文,則將目標(biāo)長度減一。
            if ((int)str[clen] > 128) { len--; }
            clen++;
        }
        #endregion

        if (clen < l)
        {
            return str.Substring(0, clen) + "...";
        }
        else
        {
            return str;
        }
    }
    /// <summary>
    /// 裁切字符串(中文按照兩個字符計算,裁切前會先過濾 Html 標(biāo)簽)
    /// </summary>
    /// <param name="str">舊字符串</param>
    /// <param name="len">新字符串長度</param>
    /// <remarks>
    /// <para>注意:<ol>
    /// <li>若字符串被截斷則會在末尾追加“...”,反之則直接返回原始字符串。</li>
    /// <li>中文按照兩個字符計算。若指定長度位置恰好只獲取半個中文字符,則會將其補全,如下面的例子:<br/>
    /// <code><![CDATA[
    /// string str = "感謝使用uoLib模塊。";
    /// string A = CutStr(str,4);   // A = "感謝..."
    /// string B = CutStr(str,5);   // B = "感謝使..."
    /// ]]></code></li>
    /// </ol>
    /// </para>
    /// </remarks>
    public static string CutStr(this string str, int len)
    {
        if (IsNullOrEmptyStr(str)) { return string.Empty; }
        else
        {
            return CutStr(str, len, false);
        }
    }
    /// <summary>
    /// 過濾HTML標(biāo)簽
    /// </summary>
    public static string HtmlFilter(this string str)
    {
        if (IsNullOrEmptyStr(str)) { return string.Empty; }
        else
        {
            Regex re = new Regex(RegexPatterns.HtmlTag, RegexOptions.IgnoreCase);
            return re.Replace(str, "");
        }
    }

    /// <summary>
    /// 獲取字符串長度。與string.Length不同的是,該方法將中文作 2 個字符計算。
    /// </summary>
    /// <param name="str">目標(biāo)字符串</param>
    /// <returns></returns>
    public static int GetLength(this string str)
    {
        if (str == null || str.Length == 0) { return 0; }

        int l = str.Length;
        int realLen = l;

        #region 計算長度
        int clen = 0;//當(dāng)前長度
        while (clen < l)
        {
            //每遇到一個中文,則將實際長度加一。
            if ((int)str[clen] > 128) { realLen++; }
            clen++;
        }
        #endregion

        return realLen;
    }

    /// <summary>
    /// 將形如 10.1MB 格式對用戶友好的文件大小字符串還原成真實的文件大小,單位為字節(jié)。
    /// </summary>
    /// <param name="formatedSize">形如 10.1MB 格式的文件大小字符串</param>
    /// <remarks>
    /// 參見:<see cref="uoLib.Common.Functions.FormatFileSize(long)"/>
    /// </remarks>
    /// <returns></returns>
    public static long GetFileSizeFromString(this string formatedSize)
    {
        if (IsNullOrEmptyStr(formatedSize)) throw new ArgumentNullException("formatedSize");

        long size;
        if (long.TryParse(formatedSize, out size)) return size;

        //去掉數(shù)字分隔符
        formatedSize = formatedSize.Replace(",", "");

        Regex re = new Regex(@"^([/d/.]+)((?:TB|GB|MB|KB|Bytes))$");
        if (re.IsMatch(formatedSize))
        {
            MatchCollection mc = re.Matches(formatedSize);
            Match m = mc[0];
            double s = double.Parse(m.Groups[1].Value);

            switch (m.Groups[2].Value)
            {
                case "TB":
                    s *= 1099511627776;
                    break;
                case "GB":
                    s *= 1073741824;
                    break;
                case "MB":
                    s *= 1048576;
                    break;
                case "KB":
                    s *= 1024;
                    break;
            }

            size = (long)s;
            return size;
        }

        throw new ArgumentException("formatedSize");
    }

    /// <summary>
    /// 根據(jù)文件夾命名規(guī)則驗證字符串是否符合文件夾格式
    /// </summary>
    public static bool IsFolderName(this string folderName)
    {
        if (IsNullOrEmptyStr(folderName)) { return false; }
        else
        {
            // 不能以 “.” 開頭
            folderName = folderName.Trim().ToLower();

            // “nul”、“aux”、“con”、“com1”、“l(fā)pt1”不能為文件夾/文件的名稱
            // 作為文件夾,只需滿足名稱不為這幾個就行。
            switch (folderName)
            {
                case "nul":
                case "aux":
                case "con":
                case "com1":
                case "lpt1":
                    return false;
                default:
                    break;
            }

            Regex re = new Regex(RegexPatterns.FolderName, RegexOptions.IgnoreCase);
            return re.IsMatch(folderName);
        }
    }

    /// <summary>
    /// 根據(jù)文件名命名規(guī)則驗證字符串是否符合文件名格式
    /// </summary>
    public static bool IsFileName(this string fileName)
    {
        if (IsNullOrEmptyStr(fileName)) { return false; }
        else
        {
            fileName = fileName.Trim().ToLower();
            // 不能以 “.” 開頭
            // 作為文件名,第一個“.” 之前不能是“nul”、“aux”、“con”、“com1”、“l(fā)pt1”
            if (fileName.StartsWith(".")
                || fileName.StartsWith("nul.")
                || fileName.StartsWith("aux.")
                || fileName.StartsWith("con.")
                || fileName.StartsWith("com1.")
                || fileName.StartsWith("lpt1.")
                ) return false;

            Regex re = new Regex(RegexPatterns.FileName, RegexOptions.IgnoreCase);
            return re.IsMatch(fileName);
        }
    }

    /// <summary>
    /// 驗證是否為合法的RGB顏色字符串
    /// </summary>
    /// <param name="color">RGB顏色,如:#00ccff | #039 | ffffcc</param>
    /// <returns></returns>
    public static bool IsRGBColor(this string color)
    {
        if (IsNullOrEmptyStr(color)) { return false; }
        else
        {
            Regex re = new Regex(RegexPatterns.HtmlColor, RegexOptions.IgnoreCase);
            return re.IsMatch(color);
        }
    }

    public static string GetJsSafeStr(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return string.Empty;

        return str.Replace("http://", "http:////").Replace("/"", "http:///"");
    }
}

 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新和县| 五莲县| 太湖县| 商南县| 且末县| 抚州市| 朝阳区| 赤峰市| 科尔| 卓资县| 安福县| 丹寨县| 沙坪坝区| 尤溪县| 兴宁市| 金川县| 宣威市| 祁阳县| 宣化县| 墨竹工卡县| 华安县| 格尔木市| 景谷| 鄢陵县| 三原县| 大厂| 安远县| 永登县| 阿坝县| 株洲市| 忻城县| 冷水江市| 东乌珠穆沁旗| 林芝县| 莱阳市| 隆德县| 拜泉县| 肥东县| 新丰县| 舟山市| 淮阳县|