标签:dex count regex def length regexp match tst The
public static string HtmlCutString(string str, int length, string character = "…") { str = System.Web.HttpUtility.HtmlDecode(str.Replace("\r\n", "")); int len = 0, tagIndex = 0, strlength = str.Length; Regex objRegExp = new Regex("(<.+?>)", RegexOptions.IgnoreCase); MatchCollection matches = objRegExp.Matches(str); for (int i = 0; i < strlength; i++) { if (matches.Count > tagIndex && i == matches[tagIndex].Index) { i += matches[tagIndex].Result("$1").Length - 1; tagIndex++; } else { if (System.Text.Encoding.Default.GetBytes(str.Substring(i, 1)).Length > 1) len += 2; else len += 1; } if (len >= length) { string other = ""; while (matches.Count > tagIndex) { other += matches[tagIndex].Value; tagIndex++; } int otherlength = other.Length; objRegExp = new Regex(@"<\s*\b(.+?)\b[^>]*?><\s*/\s*\b\1\b\s*>|<\s*\b(.+?)\b.*?/\s*>", RegexOptions.IgnoreCase); while (objRegExp.Matches(other).Count > 0) { other = objRegExp.Replace(other, ""); } other = new Regex(@"<\s*[^/]+?>", RegexOptions.IgnoreCase).Replace(other, ""); if (i + otherlength + 1 < strlength) str = str.Substring(0, i + 1 - character.Length) + character + other; else str = str.Substring(0, i + 1) + other; break; } } return str; }
标签:dex count regex def length regexp match tst The
原文地址:https://www.cnblogs.com/wangyinlon/p/12176222.html