StringExtensions.cs 14 KB

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