StringExtensions.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 Split
  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. /// </summary>
  105. public static string[] SplitLines(this string input, bool skipEmptyLines = false)
  106. => input.ReplaceLineEndings("\n").Split('\n', skipEmptyLines);
  107. #endregion
  108. #region 裁切
  109. /// <summary>
  110. /// 获取在子字符串第一次出现之前的部分,如果未找到子字符串则不裁切。
  111. /// <code>"2024/11/08".BeforeFirst("/") => "2024"</code>
  112. /// </summary>
  113. public static string BeforeFirst(this string str, string text, bool ignoreCase = false) {
  114. int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
  115. if (pos < 0) return str;
  116. return str[..pos];
  117. }
  118. /// <summary>
  119. /// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
  120. /// <code>"2024/11-08".BeforeFirstOfAny(["/", "-"]) => "2024"</code>
  121. /// </summary>
  122. public static string BeforeFirstOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
  123. if (texts == null) return str;
  124. int pos = -1;
  125. foreach (string text in texts) {
  126. if (string.IsNullOrEmpty(text)) continue;
  127. int p = str.IndexOfF(text, ignoreCase);
  128. if (p >= 0 && (pos < 0 || pos > p)) pos = p;
  129. }
  130. if (pos < 0) return str;
  131. return str[..pos];
  132. }
  133. /// <summary>
  134. /// 获取在子字符串最后一次出现之前的部分,如果未找到子字符串则不裁切。
  135. /// <code>"2024/11/08".BeforeLast("/") => "2024/11"</code>
  136. /// </summary>
  137. public static string BeforeLast(this string str, string text, bool ignoreCase = false) {
  138. int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
  139. if (pos < 0) return str;
  140. return str[..pos];
  141. }
  142. /// <summary>
  143. /// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
  144. /// <code>"2024/11-08".BeforeLastOfAny(["/", "-"]) => "2024/11"</code>
  145. /// </summary>
  146. public static string BeforeLastOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
  147. if (texts == null) return str;
  148. int pos = -1;
  149. foreach (string text in texts) {
  150. if (string.IsNullOrEmpty(text)) continue;
  151. int p = str.LastIndexOfF(text, ignoreCase);
  152. if (p >= 0 && (pos < 0 || pos < p)) pos = p;
  153. }
  154. if (pos < 0) return str;
  155. return str[..pos];
  156. }
  157. /// <summary>
  158. /// 获取在子字符串第一次出现之后的部分,如果未找到子字符串则不裁切。
  159. /// <code>"2024/11/08".AfterFirst("/") => "11/08"</code>
  160. /// </summary>
  161. public static string AfterFirst(this string str, string text, bool ignoreCase = false) {
  162. int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
  163. if (pos < 0) return str;
  164. return str[(pos + text!.Length)..];
  165. }
  166. /// <summary>
  167. /// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
  168. /// <code>"2024/11-08".AfterFirstOfAny(["/", "-"]) => "11-08"</code>
  169. /// </summary>
  170. public static string AfterFirstOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
  171. if (texts == null) return str;
  172. int pos = -1;
  173. int len = 0;
  174. foreach (string text in texts) {
  175. if (string.IsNullOrEmpty(text)) continue;
  176. int p = str.IndexOfF(text, ignoreCase);
  177. if (p >= 0 && (pos < 0 || pos > p)) {
  178. pos = p;
  179. len = text.Length;
  180. }
  181. }
  182. if (pos < 0) return str;
  183. return str[(pos + len)..];
  184. }
  185. /// <summary>
  186. /// 获取在子字符串最后一次出现之后的部分,如果未找到子字符串则不裁切。
  187. /// <code>"2024/11/08".AfterLast("/") => "08"</code>
  188. /// </summary>
  189. public static string AfterLast(this string str, string text, bool ignoreCase = false) {
  190. int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
  191. if (pos < 0) return str;
  192. return str[(pos + text!.Length)..];
  193. }
  194. /// <summary>
  195. /// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
  196. /// <code>"2024/11-08".AfterLastOfAny(["/", "-"]) => "08"</code>
  197. /// </summary>
  198. public static string AfterLastOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
  199. if (texts == null) return str;
  200. int pos = -1;
  201. int len = 0;
  202. foreach (string text in texts) {
  203. if (string.IsNullOrEmpty(text)) continue;
  204. int p = str.LastIndexOfF(text, ignoreCase);
  205. if (p >= 0 && (pos < 0 || pos < p)) {
  206. pos = p;
  207. len = text.Length;
  208. }
  209. }
  210. if (pos < 0) return str;
  211. return str[(pos + len)..];
  212. }
  213. /// <summary>
  214. /// 获取处于两个子字符串之间的部分,裁切尽可能多的内容。
  215. /// 等效于 AfterLast 后接 BeforeFirst。
  216. /// 如果未找到子字符串则不裁切。
  217. /// </summary>
  218. public static string Between(this string str, string after, string before, bool ignoreCase = false) {
  219. int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
  220. if (startPos >= 0) {
  221. startPos += after.Length;
  222. } else {
  223. startPos = 0;
  224. }
  225. int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
  226. if (endPos >= 0) {
  227. return str[startPos..endPos];
  228. } else if (startPos > 0) {
  229. return str[startPos..];
  230. } else {
  231. return str;
  232. }
  233. }
  234. #endregion
  235. #region 替换
  236. /// <summary>
  237. /// 替换字符串中的内容。
  238. /// 仅当需要替换时,才调用 <paramref name="newValueGetter"/> 获取结果字符串。
  239. /// </summary>
  240. public static string Replace(this string str, string oldValue, Func<string> newValueGetter)
  241. => str.Contains(oldValue) ? str.Replace(oldValue, newValueGetter()) : str;
  242. /// <summary>
  243. /// 将字符串中的换行符统一替换为指定字符串。
  244. /// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
  245. /// </summary>
  246. public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false)
  247. => (mergeMultiple ? regexLineEndingAndMerge : regexLineEnding).Replace(input, newValue.Replace("$", "$$")); // 避免识别成捕获组
  248. private static readonly Regex regexLineEndingAndMerge = new(@"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+", RegexOptions.Compiled);
  249. private static readonly Regex regexLineEnding = new(@"\r\n|[\n\r\f\u0085\u2028\u2029]", RegexOptions.Compiled);
  250. #endregion
  251. #region 正则
  252. /// <summary>
  253. /// 搜索字符串中所有的正则匹配项。
  254. /// </summary>
  255. public static IEnumerable<string> RegexSearch(this string str, string pattern, RegexOptions options = RegexOptions.None) {
  256. try {
  257. return Regex.Matches(str, pattern, options).Cast<Match>().Select(m => m.Value);
  258. } catch (Exception ex) {
  259. Logger.Warn(ex, $"{nameof(RegexSearch)} 失败({pattern})");
  260. return [];
  261. }
  262. }
  263. /// <summary>
  264. /// 获取字符串中的第一个正则匹配项,若无匹配或失败则返回 <see langword="null"/>。
  265. /// </summary>
  266. public static string? RegexSeek(this string str, string pattern, RegexOptions options = RegexOptions.None) {
  267. try {
  268. var match = Regex.Match(str, pattern, options);
  269. return match.Success ? match.Value : null;
  270. } catch (Exception ex) {
  271. Logger.Warn(ex, $"{nameof(RegexSeek)} 失败({pattern})");
  272. return null;
  273. }
  274. }
  275. /// <summary>
  276. /// 检查字符串是否匹配某正则模式。
  277. /// </summary>
  278. public static bool RegexCheck(this string str, string pattern, RegexOptions options = RegexOptions.None) {
  279. try {
  280. return Regex.IsMatch(str, pattern, options);
  281. } catch (Exception ex) {
  282. Logger.Warn(ex, $"{nameof(RegexCheck)} 失败({pattern})");
  283. return false;
  284. }
  285. }
  286. /// <summary>
  287. /// 进行正则替换。
  288. /// 失败时会抛出异常。
  289. /// </summary>
  290. public static string RegexReplace(this string allContents, string searchRegex, string replaceTo, RegexOptions options = RegexOptions.None) {
  291. return Regex.Replace(allContents, searchRegex, replaceTo, options);
  292. }
  293. /// <summary>
  294. /// 对每个正则匹配分别进行替换。
  295. /// 失败时会抛出异常。
  296. /// </summary>
  297. public static string RegexReplace(this string allContents, string searchRegex, MatchEvaluator replaceTo, RegexOptions options = RegexOptions.None) {
  298. return Regex.Replace(allContents, searchRegex, replaceTo, options);
  299. }
  300. #endregion
  301. /// <summary>
  302. /// 读取 <see cref="Stream"/> 中的内容,并解码为字符串。
  303. /// 会将流的位置主动重置到开头。
  304. /// </summary>
  305. public static string ReadString(this Stream stream, Encoding? encoding = null) {
  306. using var memoryStream = new MemoryStream();
  307. if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
  308. stream.CopyTo(memoryStream);
  309. return memoryStream.ToArray().GetString(encoding);
  310. }
  311. /// <summary>
  312. /// 将 <paramref name="bytes"/> 解码为字符串。
  313. /// </summary>
  314. public static string GetString(this byte[] bytes, Encoding? encoding = null) {
  315. if (encoding is not null) return encoding.GetString(bytes);
  316. int length = bytes.Length;
  317. // 根据 BOM 判断编码
  318. if (length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) {
  319. return Encoding.UTF8.GetString(bytes, 3, length - 3); // 带 BOM 的 UTF8
  320. } else if (length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) {
  321. return Encoding.BigEndianUnicode.GetString(bytes, 2, length - 2);
  322. } else if (length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) {
  323. return Encoding.Unicode.GetString(bytes, 2, length - 2);
  324. }
  325. // 无 BOM 文件:GB18030(ANSI)或 UTF8
  326. try {
  327. return new UTF8Encoding(false, true).GetString(bytes); // 不带 BOM 的 UTF8
  328. } catch (DecoderFallbackException) {
  329. return Encoding.GetEncoding("GB18030").GetString(bytes);
  330. }
  331. }
  332. /// <summary>
  333. /// 将第一个字符转换为大写,其余字符转换为小写。
  334. /// </summary>
  335. public static string Capitalize(this string word) {
  336. if (string.IsNullOrEmpty(word)) return word;
  337. return $"{word[..1].Upper()}{word[1..].Lower()}";
  338. }
  339. /// <summary>
  340. /// 将字符串统一至某个长度。
  341. /// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
  342. /// </summary>
  343. public static string EnsureLength(this string? str, char code, int length) {
  344. str ??= "";
  345. return str.Length > length ? str[..length] : str.PadLeft(length, code);
  346. }
  347. /// <summary>
  348. /// 该字符串中的字符是否均为 ASCII 字符。
  349. /// </summary>
  350. public static bool IsAsciiOnly(this string input)
  351. => input.All(c => c < 128);
  352. /// <summary>
  353. /// 计算字符串的哈希,其结果在不同环境中均能保持一致。
  354. /// </summary>
  355. public static ulong GetStableHashCode(this string str) {
  356. ulong result = 5381;
  357. foreach (char v in str) result = (result << 5) ^ result ^ v;
  358. return result ^ 0xA98F501BC684032FUL;
  359. }
  360. /// <summary>
  361. /// 将字符串转化为 JSON 对象,若失败则抛出异常。
  362. /// </summary>
  363. public static JToken? DeserializeJson(this string data) {
  364. try {
  365. return JsonConvert.DeserializeObject<JToken>(data, new JsonSerializerSettings {DateTimeZoneHandling = DateTimeZoneHandling.Local});
  366. } catch (Exception ex) {
  367. int length = (data ?? "").Length;
  368. throw new FormatException("JSON deserialize failed: " +
  369. (length > 2000
  370. ? $"{data![..500]}...(total {length} characters)...{data[^500..]}"
  371. : (data ?? "")),
  372. ex);
  373. }
  374. }
  375. /// <summary>
  376. /// 将字符串转化为 JSON 对象,若失败则抛出异常。
  377. /// </summary>
  378. public static T? DeserializeJson<T>(this string data) where T : JToken
  379. => (T?) DeserializeJson(data);
  380. }