2
0

StringUtils.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. using System.Globalization;
  2. using System.Text.RegularExpressions;
  3. namespace MeloongCore;
  4. public static class StringUtils {
  5. #region 转义
  6. /// <summary>
  7. /// WPF XML 转义。
  8. /// </summary>
  9. public static string XmlEscape(string str) {
  10. if (str.StartsWithF("{")) str = "{}" + str; // #4187
  11. return str
  12. .Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
  13. .Replace("\"", "&quot;").ReplaceLineEndings("&#xa;");
  14. }
  15. /// <summary>
  16. /// VB.NET 的 Like 关键字转义。
  17. /// </summary>
  18. public static string LikePatternEscape(string input) {
  19. var builder = new StringBuilder();
  20. foreach (char c in input) {
  21. if (c is '[' or ']' or '*' or '?' or '#') {
  22. builder.Append('[').Append(c).Append(']');
  23. } else {
  24. builder.Append(c);
  25. }
  26. }
  27. return builder.ToString();
  28. }
  29. /// <summary>
  30. /// 正则表达式转义。
  31. /// 等同于 <see cref="Regex.Escape"/>。
  32. /// </summary>
  33. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  34. public static string RegexEscape(string value)
  35. => Regex.Escape(value);
  36. /// <summary>
  37. /// 正则表达式去转义。
  38. /// 等同于 <see cref="Regex.Unescape"/>。
  39. /// </summary>
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public static string RegexUnescape(string value)
  42. => Regex.Unescape(value);
  43. /// <summary>
  44. /// URL 转义。
  45. /// 等同于 <see cref="Uri.EscapeDataString"/>。
  46. /// </summary>
  47. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  48. public static string UrlEscape(string value)
  49. => Uri.EscapeDataString(value);
  50. /// <summary>
  51. /// URL 去转义。
  52. /// 等同于 <see cref="Uri.UnescapeDataString"/>。
  53. /// </summary>
  54. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  55. public static string UrlUnescape(string value)
  56. => Uri.UnescapeDataString(value);
  57. /// <summary>
  58. /// 表单转义。
  59. /// 等同于 <see cref="WebUtility.UrlEncode"/>。
  60. /// </summary>
  61. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  62. public static string FormUrlEscape(string value)
  63. => WebUtility.UrlEncode(value)!;
  64. /// <summary>
  65. /// 表单去转义。
  66. /// 等同于 <see cref="WebUtility.UrlDecode"/>。
  67. /// </summary>
  68. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  69. public static string FormUrlUnescape(string value)
  70. => WebUtility.UrlDecode(value);
  71. /// <summary>
  72. /// HTML 转义。
  73. /// 等同于 <see cref="WebUtility.HtmlEncode"/>。
  74. /// </summary>
  75. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  76. public static string HtmlEscape(string value)
  77. => WebUtility.HtmlEncode(value);
  78. /// <summary>
  79. /// HTML 去转义。
  80. /// 等同于 <see cref="WebUtility.HtmlDecode"/>。
  81. /// </summary>
  82. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  83. public static string HtmlUnescape(string value)
  84. => WebUtility.HtmlDecode(value);
  85. #endregion
  86. #region 格式化
  87. /// <summary>
  88. /// 将文件大小的字节数格式化为适合阅读的文本,如 <c>"1.28 M"</c>、<c>"128 G"</c>。
  89. /// </summary>
  90. public static string FormatByteSize(long byteSize) {
  91. var sign = byteSize < 0 ? "-" : "";
  92. if (byteSize < 0) byteSize *= -1;
  93. if (byteSize < 1000) { // B 级
  94. return $"{sign}{byteSize} B";
  95. } else if (byteSize < 1024 * 1000) { // K 级
  96. var roundResult = Math.Round(byteSize / 1024D).ToString(CultureInfo.InvariantCulture);
  97. return $"{sign}{Math.Round(byteSize / 1024D, (3 - roundResult.Length).Clamp(0, 2))} K";
  98. } else if (byteSize < 1024 * 1024 * 1000) { // M 级
  99. var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
  100. return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} M";
  101. } else { // G 级
  102. var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
  103. return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} G";
  104. }
  105. }
  106. /// <summary>
  107. /// 将时间间隔格式化为适合阅读的文本。
  108. /// <para/>若指定了 <paramref name="isShort"/>,则只使用一个单位,如 <c>"5 分钟前"</c>,否则有可能会使用两个单位,如 <c>"5 分 10 秒前"</c>。
  109. /// </summary>
  110. public static string FormatTimeSpan(TimeSpan span, bool isShort) {
  111. var suffix = span.TotalMilliseconds > 0 ? "后" : "前";
  112. if (span.TotalMilliseconds < 0) span = -span;
  113. var totalMonths = (int) Math.Floor(span.Days / 30D);
  114. if (isShort) {
  115. if (totalMonths >= 12) {
  116. // 1+ 年,“3 年”
  117. return $"{Math.Floor(totalMonths / 12D)} 年{suffix}";
  118. } else if (totalMonths >= 2) {
  119. // 2~11 月,“5 个月”
  120. return $"{totalMonths} 个月{suffix}";
  121. } else if (span.TotalDays >= 2) {
  122. // 2 天 ~ 2 月,“23 天”
  123. return $"{span.Days} 天{suffix}";
  124. } else if (span.TotalHours >= 1) {
  125. // 1 小时 ~ 2 天,“15 小时”
  126. return $"{span.Hours} 小时{suffix}";
  127. } else if (span.TotalMinutes >= 1) {
  128. // 1 分钟 ~ 1 小时,“49 分钟”
  129. return $"{span.Minutes} 分钟{suffix}";
  130. } else if (span.TotalSeconds >= 1) {
  131. // 1 秒 ~ 1 分钟,“23 秒”
  132. return $"{span.Seconds} 秒{suffix}";
  133. } else {
  134. // 不到 1 秒
  135. return $"1 秒{suffix}";
  136. }
  137. } else {
  138. if (totalMonths >= 61) {
  139. // 5+ 年,“5 年”
  140. return $"{Math.Floor(totalMonths / 12D)} 年{suffix}";
  141. } else if (totalMonths >= 12) {
  142. // 12~60 月,“1 年 2 个月”
  143. return $"{Math.Floor(totalMonths / 12D)} 年{(totalMonths % 12 > 0 ? $" {totalMonths % 12} 个月" : "")}{suffix}";
  144. } else if (totalMonths >= 4) {
  145. // 4~11 月,“5 个月”
  146. return $"{totalMonths} 个月{suffix}";
  147. } else if (totalMonths >= 1) {
  148. // 1~4 月,“2 个月 13 天”
  149. return $"{totalMonths} 月{(span.Days % 30 > 0 ? $" {span.Days % 30} 天" : "")}{suffix}";
  150. } else if (span.TotalDays >= 4) {
  151. // 4~30 天,“23 天”
  152. return $"{span.Days} 天{suffix}";
  153. } else if (span.TotalDays >= 1) {
  154. // 1~3 天,“2 天 20 小时”
  155. return $"{span.Days} 天{(span.Hours > 0 ? $" {span.Hours} 小时" : "")}{suffix}";
  156. } else if (span.TotalHours >= 10) {
  157. // 10 小时 ~ 1 天,“15 小时”
  158. return $"{span.Hours} 小时{suffix}";
  159. } else if (span.TotalHours >= 1) {
  160. // 1~10 小时,“1 小时 20 分钟”
  161. return $"{span.Hours} 小时{(span.Minutes > 0 ? $" {span.Minutes} 分钟" : "")}{suffix}";
  162. } else if (span.TotalMinutes >= 10) {
  163. // 10 分钟 ~ 1 小时,“49 分钟”
  164. return $"{span.Minutes} 分钟{suffix}";
  165. } else if (span.TotalMinutes >= 1) {
  166. // 1~10 分钟,“9 分 23 秒”
  167. return $"{span.Minutes} 分{(span.Seconds > 0 ? $" {span.Seconds} 秒" : "")}{suffix}";
  168. } else if (span.TotalSeconds >= 1) {
  169. // 1 秒 ~ 1 分钟,“23 秒”
  170. return $"{span.Seconds} 秒{suffix}";
  171. } else {
  172. // 不到 1 秒
  173. return $"1 秒{suffix}";
  174. }
  175. }
  176. }
  177. #endregion
  178. /// <summary>
  179. /// 将字符串解析为版本号。
  180. /// 允许缺少任意多个段,且会将缺失的段不为 0,而不是 -1。例如,"2" 会被解析为 2.0.0.0。
  181. /// </summary>
  182. public static Version ParseVersionWithDefaults(string value) {
  183. while (value.Count(c => c == '.') < 3) value += ".0";
  184. return Version.Parse(value);
  185. }
  186. }