StringExtensions.cs 18 KB

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