StringExtensions.cs 18 KB

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