StringExtensions.cs 17 KB

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