SoFunction
Updated on 2025-03-07

Common operation tool code sharing for C# strings


public static class ExtendedString
{
    /// <summary>
/// Verify whether the string consists of a positive and negative sign (+-), a number, and a decimal point, and at most one decimal point
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumeric(this string str)
    {
        Regex regex = new Regex(@"^[+-]?\d+[.]?\d*$");
        return (str);           
    }

    /// <summary>
/// Verify whether the string is composed only of [0-9]
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumericOnly(this string str)
    {
        Regex regex = new Regex("[0-9]");
        return (str);
    }

    /// <summary>
/// Verify whether the string is composed of letters and numbers
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumericOrLetters(this string str)
    {
        Regex regex = new Regex("[a-zA-Z0-9]");
        return (str);
    }

    /// <summary>
/// Verify that it is an empty string. If there is no need to cut spaces at both ends, it is recommended to use (string) directly.
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    /// <remarks>
/// Unlike (string), this method will add a step to Trim operation. For example, IsNullOrEmptyStr(" ") will return true.
    /// </remarks>
    public static bool IsNullOrEmptyStr(this string str)
    {
        if ((str)) { return true; }
        if (().Length == 0) { return true; }
        return false;
    }

    /// <summary>
/// Crop string (calculated in Chinese according to two characters)
    /// </summary>
/// <param name="str">Old string</param>
/// <param name="len">New string length</param>
/// When <param name="HtmlEnable"> is false, filter the Html tag and then crop it. Otherwise, keep the Html tag. </param>
    /// <remarks>
/// <para>Note: <ol>
/// <li>If the string is truncated, "..." will be added at the end, otherwise it will directly return to the original string. </li>
When the parameter <paramref name="HtmlEnable"/> is false, the <see cref=""/> will be called to filter out the Html tag and then crop. </li>
/// <li>Chinese is calculated based on two characters. If the specified length position only takes half a Chinese character, it will be completed, as in the following example:
    /// <code><![CDATA[
/// string str = "Thanks for using uoLib.";
/// string A = CutStr(str,4);   // A = "Thank you..."
/// string B = CutStr(str,5);   // B = "Thank you for making..."
    /// ]]></code></li>
    /// </ol>
    /// </para>
    /// </remarks>
    public static string CutStr(this string str, int len, bool HtmlEnable)
    {
        if (str == null || == 0 || len <= 0) { return ; }

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

#region Calculate length
int clen = 0;//Current length
        while (clen < len && clen < l)
        {
//Every time you encounter one Chinese, reduce the target length by one.
            if ((int)str[clen] > 128) { len--; }
            clen++;
        }
        #endregion

        if (clen < l)
        {
            return (0, clen) + "...";
        }
        else
        {
            return str;
        }
    }
    /// <summary>
/// Crop string (Chinese is calculated based on two characters, and the Html tag will be filtered before cropping)
    /// </summary>
/// <param name="str">Old string</param>
/// <param name="len">New string length</param>
    /// <remarks>
/// <para>Note: <ol>
/// <li>If the string is truncated, "..." will be added at the end, otherwise it will directly return to the original string. </li>
/// <li>Chinese is calculated based on two characters. If the specified length position only takes half a Chinese character, it will be completed, as in the following example:
    /// <code><![CDATA[
/// string str = "Thanks for using the uoLib module.";
/// string A = CutStr(str,4);   // A = "Thank you..."
/// string B = CutStr(str,5);   // B = "Thank you for making..."
    /// ]]></code></li>
    /// </ol>
    /// </para>
    /// </remarks>
    public static string CutStr(this string str, int len)
    {
        if (IsNullOrEmptyStr(str)) { return ; }
        else
        {
            return CutStr(str, len, false);
        }
    }
    /// <summary>
/// Filter HTML tags
    /// </summary>
    public static string HtmlFilter(this string str)
    {
        if (IsNullOrEmptyStr(str)) { return ; }
        else
        {
            Regex re = new Regex(, );
            return (str, "");
        }
    }

    /// <summary>
/// Get the string length. Unlike this method calculates 2 characters in Chinese.
    /// </summary>
/// <param name="str">Target string</param>
    /// <returns></returns>
    public static int GetLength(this string str)
    {
        if (str == null || == 0) { return 0; }

        int l = ;
        int realLen = l;

#region Calculate length
int clen = 0;//Current length
        while (clen < l)
        {
//Every time you encounter one Chinese, add the actual length by one.
            if ((int)str[clen] > 128) { realLen++; }
            clen++;
        }
        #endregion

        return realLen;
    }

    /// <summary>
/// Restore a user-friendly file size string in 10.1MB format to the real file size in bytes.
    /// </summary>
/// <param name="formatedSize">File size string in 10.1MB format</param>
    /// <remarks>
/// See: <see cref="(long)"/>
    /// </remarks>
    /// <returns></returns>
    public static long GetFileSizeFromString(this string formatedSize)
    {
        if (IsNullOrEmptyStr(formatedSize)) throw new ArgumentNullException("formatedSize");

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

//Remove the number separator
        formatedSize = (",", "");

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

            switch ([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>
/// Verify whether the string conforms to the folder format according to the folder naming rules
    /// </summary>
    public static bool IsFolderName(this string folderName)
    {
        if (IsNullOrEmptyStr(folderName)) { return false; }
        else
        {
// Cannot start with "."
            folderName = ().ToLower();

// "nul", "aux", "con", "com1", "lpt1" cannot be the name of the folder/file
As a folder, just need to satisfy the name not being these.
            switch (folderName)
            {
                case "nul":
                case "aux":
                case "con":
                case "com1":
                case "lpt1":
                    return false;
                default:
                    break;
            }

            Regex re = new Regex(, );
            return (folderName);
        }
    }

    /// <summary>
/// Verify whether the string conforms to the file name format according to the file name naming rules
    /// </summary>
    public static bool IsFileName(this string fileName)
    {
        if (IsNullOrEmptyStr(fileName)) { return false; }
        else
        {
            fileName = ().ToLower();
// Cannot start with "."
// As the file name, the first "." cannot be "nul", "aux", "con", "com1", "lpt1" before
            if ((".")
                || ("nul.")
                || ("aux.")
                || ("con.")
                || ("com1.")
                || ("lpt1.")
                ) return false;

            Regex re = new Regex(, );
            return (fileName);
        }
    }

    /// <summary>
/// Verify that it is a legal RGB color string
    /// </summary>
/// <param name="color">RGB color, such as: #00ccff | #039 | ffffcc</param>
    /// <returns></returns>
    public static bool IsRGBColor(this string color)
    {
        if (IsNullOrEmptyStr(color)) { return false; }
        else
        {
            Regex re = new Regex(, );
            return (color);
        }
    }

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

        return ("\\", "\\\\").Replace("\"", "\\\"");
    }
}