StringExtensions.cs 13 KB

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