2
0

StringExtensions.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using System.Text.RegularExpressions;
  2. namespace MeloongCore.Extensions;
  3. public static class StringExtensions {
  4. #region 区域性 / 大小写 简化
  5. /// <summary>
  6. /// 非区域性的 <see cref="string.StartsWith(string)"/>。
  7. /// </summary>
  8. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  9. public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false)
  10. => value?.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
  11. /// <summary>
  12. /// 判断字符串是否以 <paramref name="prefix"/> 开头。
  13. /// </summary>
  14. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  15. public static bool StartsWithF(this string? value, char prefix, bool ignoreCase = false)
  16. => value?.StartsWith(prefix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
  17. /// <summary>
  18. /// 非区域性的 <see cref="string.EndsWith(string)"/>。
  19. /// </summary>
  20. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  21. public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false)
  22. => value?.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
  23. /// <summary>
  24. /// 判断字符串是否以 <paramref name="suffix"/> 结尾。
  25. /// </summary>
  26. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  27. public static bool EndsWithF(this string? value, char suffix, bool ignoreCase = false)
  28. => value?.EndsWith(suffix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
  29. /// <summary>
  30. /// 忽略大小写的 <see cref="string.Contains(string)"/>。
  31. /// </summary>
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. public static bool ContainsIgnoreCase(this string value, string subString)
  34. => value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
  35. /// <summary>
  36. /// 非区域性的 <see cref="string.IndexOf(string)"/>。
  37. /// </summary>
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public static int IndexOfF(this string value, string subString, bool ignoreCase = false)
  40. => value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
  41. /// <summary>
  42. /// 非区域性的 <see cref="string.IndexOf(string, int)"/>。
  43. /// </summary>
  44. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  45. public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false)
  46. => value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
  47. /// <summary>
  48. /// 非区域性的 <see cref="string.LastIndexOf(string)"/>。
  49. /// </summary>
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false)
  52. => value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
  53. /// <summary>
  54. /// 非区域性的 <see cref="string.LastIndexOf(string, int)"/>。
  55. /// </summary>
  56. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  57. public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false)
  58. => value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
  59. /// <summary>
  60. /// <see cref="string.ToLowerInvariant"/> 的简略写法。
  61. /// </summary>
  62. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  63. public static string Lower(this string str)
  64. => str.ToLowerInvariant();
  65. /// <summary>
  66. /// <see cref="string.ToUpperInvariant"/> 的简略写法。
  67. /// </summary>
  68. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  69. public static string Upper(this string str)
  70. => str.ToUpperInvariant();
  71. #endregion
  72. #region 分割与裁切
  73. /// <summary>
  74. /// 分割字符串。
  75. /// 若原始字符串为空,则返回 {""}。
  76. /// </summary>
  77. public static string[] Split(this string fullStr, string splitStr) {
  78. if (splitStr.IsSingle()) {
  79. return fullStr.Split(splitStr[0]);
  80. } else {
  81. return fullStr.Split([splitStr], StringSplitOptions.None);
  82. }
  83. }
  84. /// <summary>
  85. /// 获取在子字符串第一次出现之前的部分,如果未找到子字符串则不裁切。
  86. /// <code>"2024/11/08".BeforeFirst("/") => "2024"</code>
  87. /// </summary>
  88. public static string BeforeFirst(this string str, string text, bool ignoreCase = false) {
  89. int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
  90. if (pos < 0) return str;
  91. return str.Substring(0, pos);
  92. }
  93. /// <summary>
  94. /// 获取在子字符串最后一次出现之前的部分,如果未找到子字符串则不裁切。
  95. /// <code>"2024/11/08".BeforeLast("/") => "2024/11"</code>
  96. /// </summary>
  97. public static string BeforeLast(this string str, string text, bool ignoreCase = false) {
  98. int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
  99. if (pos < 0) return str;
  100. return str.Substring(0, pos);
  101. }
  102. /// <summary>
  103. /// 获取在子字符串第一次出现之后的部分,如果未找到子字符串则不裁切。
  104. /// <code>"2024/11/08".AfterFirst("/") => "11/08"</code>
  105. /// </summary>
  106. public static string AfterFirst(this string str, string text, bool ignoreCase = false) {
  107. int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
  108. if (pos < 0) return str;
  109. return str.Substring(pos + text!.Length);
  110. }
  111. /// <summary>
  112. /// 获取在子字符串最后一次出现之后的部分,如果未找到子字符串则不裁切。
  113. /// <code>"2024/11/08".AfterLast("/") => "08"</code>
  114. /// </summary>
  115. public static string AfterLast(this string str, string text, bool ignoreCase = false) {
  116. int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
  117. if (pos < 0) return str;
  118. return str.Substring(pos + text!.Length);
  119. }
  120. /// <summary>
  121. /// 获取处于两个子字符串之间的部分,裁切尽可能多的内容。
  122. /// 等效于 AfterLast 后接 BeforeFirst。
  123. /// 如果未找到子字符串则不裁切。
  124. /// </summary>
  125. public static string Between(this string str, string after, string before, bool ignoreCase = false) {
  126. int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
  127. if (startPos >= 0) {
  128. startPos += after.Length;
  129. } else {
  130. startPos = 0;
  131. }
  132. int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
  133. if (endPos >= 0) {
  134. return str.Substring(startPos, endPos - startPos);
  135. } else if (startPos > 0) {
  136. return str.Substring(startPos);
  137. } else {
  138. return str;
  139. }
  140. }
  141. #endregion
  142. #region 替换
  143. /// <summary>
  144. /// 替换字符串中的内容。
  145. /// 仅当需要替换时,才调用 <paramref name="newValueGetter"/> 获取结果字符串。
  146. /// </summary>
  147. public static string Replace(this string str, string oldValue, Func<string> newValueGetter)
  148. => str.Contains(oldValue) ? str.Replace(oldValue, newValueGetter()) : str;
  149. /// <summary>
  150. /// 将字符串中的换行符统一替换为指定字符。
  151. /// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
  152. /// </summary>
  153. public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false)
  154. => (mergeMultiple ? regexLineEndingAndMerge : regexLineEnding).Replace(input, newValue.Replace("$", "$$")); // 避免识别成捕获组
  155. private static readonly Regex regexLineEndingAndMerge = new(@"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+", RegexOptions.Compiled);
  156. private static readonly Regex regexLineEnding = new(@"\r\n|[\n\r\f\u0085\u2028\u2029]", RegexOptions.Compiled);
  157. /// <summary>
  158. /// 将字符串分割为多行。
  159. /// </summary>
  160. public static string[] SplitLines(this string input, bool skipEmptyLines = false)
  161. => input.ReplaceLineEndings("\n").Split(['\n'], skipEmptyLines ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
  162. #endregion
  163. #region 正则
  164. /// <summary>
  165. /// 搜索字符串中所有的正则匹配项。
  166. /// </summary>
  167. public static IEnumerable<string> RegexSearch(this string str, string pattern, RegexOptions options = RegexOptions.None) {
  168. try {
  169. return Regex.Matches(str, pattern, options).Cast<Match>().Select(m => m.Value);
  170. } catch (Exception ex) {
  171. Logger.Warn(ex, $"{nameof(RegexSearch)} 失败({pattern})");
  172. return [];
  173. }
  174. }
  175. /// <summary>
  176. /// 获取字符串中的第一个正则匹配项,若无匹配或失败则返回 <see langword="null"/>。
  177. /// </summary>
  178. public static string? RegexSeek(this string str, string pattern, RegexOptions options = RegexOptions.None) {
  179. try {
  180. var match = Regex.Match(str, pattern, options);
  181. return match.Success ? match.Value : null;
  182. } catch (Exception ex) {
  183. Logger.Warn(ex, $"{nameof(RegexSeek)} 失败({pattern})");
  184. return null;
  185. }
  186. }
  187. /// <summary>
  188. /// 检查字符串是否匹配某正则模式。
  189. /// </summary>
  190. public static bool RegexCheck(this string str, string pattern, RegexOptions options = RegexOptions.None) {
  191. try {
  192. return Regex.IsMatch(str, pattern, options);
  193. } catch (Exception ex) {
  194. Logger.Warn(ex, $"{nameof(RegexCheck)} 失败({pattern})");
  195. return false;
  196. }
  197. }
  198. /// <summary>
  199. /// 进行正则替换。
  200. /// 失败时会抛出异常。
  201. /// </summary>
  202. public static string RegexReplace(this string allContents, string searchRegex, string replaceTo, RegexOptions options = RegexOptions.None) {
  203. return Regex.Replace(allContents, searchRegex, replaceTo, options);
  204. }
  205. /// <summary>
  206. /// 对每个正则匹配分别进行替换。
  207. /// 失败时会抛出异常。
  208. /// </summary>
  209. public static string RegexReplace(this string allContents, string searchRegex, MatchEvaluator replaceTo, RegexOptions options = RegexOptions.None) {
  210. return Regex.Replace(allContents, searchRegex, replaceTo, options);
  211. }
  212. #endregion
  213. #region 读取为字符串
  214. /// <summary>
  215. /// 读取 <see cref="Stream"/> 中的内容,并解码为字符串。
  216. /// 会将流的位置主动重置到开头。
  217. /// </summary>
  218. public static string ReadString(this Stream stream, Encoding? encoding = null) {
  219. using var memoryStream = new MemoryStream();
  220. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  221. stream.CopyTo(memoryStream);
  222. return memoryStream.ToArray().GetString(encoding);
  223. }
  224. /// <summary>
  225. /// 将 <paramref name="bytes"/> 解码为字符串。
  226. /// </summary>
  227. public static string GetString(this byte[] bytes, Encoding? encoding = null) {
  228. if (encoding is not null) return encoding.GetString(bytes);
  229. int length = bytes.Length;
  230. // 根据 BOM 判断编码
  231. if (length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) {
  232. return Encoding.UTF8.GetString(bytes, 3, length - 3); // 带 BOM 的 UTF8
  233. } else if (length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) {
  234. return Encoding.BigEndianUnicode.GetString(bytes, 2, length - 2);
  235. } else if (length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) {
  236. return Encoding.Unicode.GetString(bytes, 2, length - 2);
  237. }
  238. // 无 BOM 文件:GB18030(ANSI)或 UTF8
  239. try {
  240. return new UTF8Encoding(false, true).GetString(bytes); // 不带 BOM 的 UTF8
  241. } catch (DecoderFallbackException) {
  242. return Encoding.GetEncoding("GB18030").GetString(bytes);
  243. }
  244. }
  245. #endregion
  246. /// <summary>
  247. /// 将第一个字符转换为大写,其余字符转换为小写。
  248. /// </summary>
  249. public static string Capitalize(this string word) {
  250. if (string.IsNullOrEmpty(word)) return word;
  251. return $"{word.Substring(0, 1).Upper()}{word.Substring(1).Lower()}";
  252. }
  253. /// <summary>
  254. /// 将字符串统一至某个长度。
  255. /// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
  256. /// </summary>
  257. public static string EnsureLength(this string? str, char code, int length) {
  258. str ??= "";
  259. return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
  260. }
  261. /// <summary>
  262. /// 该字符串中的字符是否均为 ASCII 字符。
  263. /// </summary>
  264. public static bool IsAsciiOnly(this string input)
  265. => input.All(c => c < 128);
  266. }