使用正则表达式截取字符串显示内容长度

来源:互联网 发布:澳洲保健品 知乎 编辑:程序博客网 时间:2024/06/05 11:53
    #region 使用正则表达式截取字符串显示内容长度    /// <summary>    /// 使用正则表达式截取字符串显示内容长度    /// </summary>    /// <param name="content">要切取的字符串</param>    /// <param name="length">要得到的长度</param>    /// <returns>切取后的字符串</returns>    public static string CutString2(object content, int length)    {        string temp = content.ToString().Replace("<br/>", "").Replace("<br>", "");//先替换换行标签,保证不出现换行        /*         * 参数说明:要处理的字符串,符合条件的表达式[汉字],         * 替换的字符[内容随意写但是要两个字符,因为一个中文对应两个字符,不区分大小写]         */        if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= length)        {            return temp;        }        for (int i = temp.Length; i >= 0; i--)        {            temp = temp.Substring(0, i);            if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= length - 3)            {                return temp + "...";            }        }        return "";    }    #endregion

原创粉丝点击