You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1370 lines
49 KiB

5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
  1. using Apewer.Internals;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. namespace Apewer
  9. {
  10. /// <summary>文本实用工具。</summary>
  11. public static class TextUtility
  12. {
  13. const string LetterChars = LowerCase + UpperCase;
  14. const string BlankChars = "  \n\r\t\f\b\a"; // 在 IsBlank 和 Trim 中视为空白的字符。
  15. const string LineFeed = "\r\n"; // 换行符,由 ASCII 13 和 ASCII 10 组成。
  16. /// <summary>半角空格。</summary>
  17. public const string Space = " ";
  18. /// <summary>全角空格。</summary>
  19. public const string SpaceSbc = " ";
  20. /// <summary>十进制字符。</summary>
  21. public const string Decimal = "0123456789";
  22. /// <summary>十六进制字符。</summary>
  23. public const string Hexadecimal = "0123456789abcdef";
  24. /// <summary>小写字母。</summary>
  25. public const string LowerCase = "abcdefghijklmnopqrstuvwxyz";
  26. /// <summary>大写字母。</summary>
  27. public const string UpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  28. /// <summary>UTF-8 BOM。</summary>
  29. public static byte[] Bom { get => new byte[] { 0xEF, 0xBB, 0xBF }; }
  30. /// <summary>CRLF。</summary>
  31. public const string CRLF = "\r\n";
  32. /// <summary>CR。</summary>
  33. public const char CR = '\r';
  34. /// <summary>LF。</summary>
  35. public const char LF = '\n';
  36. /// <summary>长度为 0 的空字符串。</summary>
  37. public const string Empty = "";
  38. /// <summary>无效指针。</summary>
  39. public const string Null = null;
  40. /// <summary>返回表示指定对象的字符串。</summary>
  41. public static string Text(object value)
  42. {
  43. if (value is string str) return str;
  44. if (value == null) return null;
  45. if (value.Equals(DBNull.Value)) return null;
  46. if (value is Type t) return t.Name;
  47. if (value is char[] chars) return new string(chars);
  48. var type = value.GetType();
  49. var toString = type.GetMethod(nameof(object.ToString), Type.EmptyTypes);
  50. if (toString.DeclaringType.Equals(type))
  51. {
  52. try { return value.ToString(); }
  53. catch { return null; }
  54. }
  55. return "<" + type.Name + ">";
  56. }
  57. /// <summary>字符串为空。</summary>
  58. public static bool IsEmpty(string text) => text == null || text == Empty;
  59. /// <summary>字符串不为空。</summary>
  60. public static bool NotEmpty(string text) => text != null && text != Empty;
  61. /// <summary>字符串为空,或只含有空白字符。</summary>
  62. public static bool IsBlank(string text)
  63. {
  64. if (IsEmpty(text)) return true;
  65. var length = text.Length;
  66. var bcs = BlankChars.ToCharArray();
  67. var bcl = bcs.Length;
  68. bool b;
  69. char c;
  70. for (var i = 0; i < length; i++)
  71. {
  72. c = text[i];
  73. b = false;
  74. for (var j = 0; j < bcl; j++)
  75. {
  76. if (c == bcs[j])
  77. {
  78. b = true;
  79. break;
  80. }
  81. }
  82. if (!b) return false;
  83. }
  84. return true;
  85. }
  86. /// <summary>字符串不为空,切含有非空白字符。</summary>
  87. public static bool NotBlank(string text) => !IsBlank(text);
  88. /// <summary>获取文本的 Int32 哈希。</summary>
  89. private static int HashCode(string text)
  90. {
  91. if (text == null) return 0;
  92. int hash = 0;
  93. var length = text.Length;
  94. for (int i = 0; i < length; i++)
  95. {
  96. hash = 31 * hash + text[i];
  97. }
  98. return hash;
  99. }
  100. private static string PrivateJoin(string separator, IEnumerable cells)
  101. {
  102. if (cells == null) return Empty;
  103. if (cells is string str) return str ?? "";
  104. var sb = new StringBuilder();
  105. var first = true;
  106. var hasSeparator = !string.IsNullOrEmpty(separator);
  107. foreach (var cell in cells)
  108. {
  109. if (cell == null) continue;
  110. var text = null as string;
  111. if (cell is string) text = cell as string;
  112. else if (cell is Type type) text = type.Name;
  113. else cell.ToString();
  114. if (string.IsNullOrEmpty(text)) continue;
  115. if (!first && hasSeparator) sb.Append(separator);
  116. first = false;
  117. sb.Append(text);
  118. }
  119. var result = sb.ToString();
  120. return result;
  121. }
  122. /// <summary>合并为字符串。</summary>
  123. public static string Merge(params object[] cells) => Join(null, cells);
  124. /// <summary>合并为字符串。</summary>
  125. public static string Join(string separator, params object[] cells)
  126. {
  127. if (cells == null) return Empty;
  128. while (cells.Length == 1)
  129. {
  130. var first = cells[0];
  131. if (first.IsNull()) return Empty;
  132. if (first is string str) return str ?? Empty;
  133. if (first is IEnumerable<char> chars)
  134. {
  135. var list = new List<char>();
  136. foreach (var @char in chars) list.Add(@char);
  137. return new string(list.ToArray());
  138. }
  139. if (!first.GetType().IsValueType && first is IEnumerable enumerable)
  140. {
  141. var list = new List<object>();
  142. foreach (var item in enumerable) list.Add(item);
  143. cells = list.ToArray();
  144. continue;
  145. }
  146. break;
  147. }
  148. {
  149. var sb = new StringBuilder();
  150. var first = true;
  151. var hasSeparator = !string.IsNullOrEmpty(separator);
  152. foreach (var cell in cells)
  153. {
  154. if (cell.IsNull()) continue;
  155. var text = null as string;
  156. if (cell is string str) text = str;
  157. else if (cell is char[] chars) text = new string(chars);
  158. else text = Text(cell);
  159. if (string.IsNullOrEmpty(text)) continue;
  160. if (hasSeparator)
  161. {
  162. if (first) first = false;
  163. else sb.Append(separator);
  164. }
  165. sb.Append(text);
  166. }
  167. var result = sb.ToString();
  168. return result;
  169. }
  170. }
  171. /// <summary>重复指定字符,直到达到指定长度。</summary>
  172. /// <param name="cell">要重复的字符。</param>
  173. /// <param name="count">重复的次数。</param>
  174. public static string Duplicate(char cell, int count)
  175. {
  176. if (count < 1) return Empty;
  177. var chars = new char[count];
  178. for (var i = 0; i < count; i++) chars[i] = cell;
  179. return new string(chars);
  180. }
  181. /// <summary>重复指定字符串,直到达到指定长度。</summary>
  182. /// <param name="cell">要重复的字符串。</param>
  183. /// <param name="count">重复的次数。</param>
  184. public static string Duplicate(string cell, int count)
  185. {
  186. if (IsEmpty(cell) || count < 1) return Empty;
  187. var length = cell.Length;
  188. var total = length * count;
  189. var output = new char[total];
  190. var input = cell.ToCharArray();
  191. for (var i = 0; i < count; i++)
  192. {
  193. Array.Copy(input, 0, output, length * i, length);
  194. }
  195. return new string(output);
  196. }
  197. /// <summary>将文本以转换为字节数组。默认 Encoding 为 UTF-8。</summary>
  198. public static byte[] Bytes(string text, Encoding encoding = null)
  199. {
  200. if (text == null || text == Empty) return BytesUtility.Empty;
  201. try { return (encoding ?? Encoding.UTF8).GetBytes(text); }
  202. catch { return BytesUtility.Empty; }
  203. }
  204. /// <summary>将字节数组转换为文本。默认 Encoding 为 UTF-8。</summary>
  205. public static string FromBytes(byte[] bytes, Encoding encoding = null)
  206. {
  207. if (bytes == null || bytes.LongLength < 1L) return Empty;
  208. // 计算非零字节的长度
  209. var count = 0;
  210. for (var i = 0; i < bytes.Length; i++)
  211. {
  212. if (bytes[i] == 0) continue;
  213. count++;
  214. }
  215. if (count < 1) return Empty;
  216. // 转换
  217. if (encoding == null) encoding = Encoding.UTF8;
  218. try
  219. {
  220. var result = encoding.GetString(bytes, 0, count);
  221. return result;
  222. }
  223. catch { return Empty; }
  224. }
  225. /// <summary>将明文文本以 UTF-8 转换为 Base64 文本。</summary>
  226. public static string ToBase64(string plain)
  227. {
  228. if (plain == null || plain == Empty) return Empty;
  229. return BytesUtility.ToBase64(Bytes(plain));
  230. }
  231. /// <summary>将 Base64 文本以 UTF-8 转换为明文文本。</summary>
  232. public static string FromBase64(string cipher)
  233. {
  234. if (cipher == null || cipher == Empty) return Empty;
  235. return FromBytes(BytesUtility.FromBase64(cipher));
  236. }
  237. /// <summary>从字符串中删除子字符串。</summary>
  238. /// <param name="text">要查询的字符串。</param>
  239. /// <param name="sub">子字符串。</param>
  240. /// <param name="ignoreCase">是否忽略大小写。</param>
  241. /// <returns>删除子字符串后的父字符串。</returns>
  242. private static string Exlude(string text, string sub, bool ignoreCase = false)
  243. {
  244. if (string.IsNullOrEmpty(text)) return "";
  245. if (string.IsNullOrEmpty(sub)) return text;
  246. try
  247. {
  248. string vp = text;
  249. string vs = sub;
  250. string vr = "";
  251. int vl;
  252. int vi;
  253. if (ignoreCase)
  254. {
  255. vp = TextHelper.LCase(vp);
  256. vs = TextHelper.LCase(vs);
  257. }
  258. vl = vs.Length;
  259. vi = 1;
  260. while (vi <= (vp.Length - vl + 1))
  261. {
  262. if (TextHelper.Middle(vp, vi, vl) == vs)
  263. {
  264. vi = vi + vl;
  265. }
  266. else
  267. {
  268. vr = vr + TextHelper.Middle(text, vi, 1);
  269. vi = vi + 1;
  270. }
  271. }
  272. return vr;
  273. }
  274. catch { return text; }
  275. }
  276. /// <summary>替换字符串中的子字符串。</summary>
  277. /// <param name="text">要查询的字符串。</param>
  278. /// <param name="new">新子字符串,保留大小写。</param>
  279. /// <param name="old">原子字符串。</param>
  280. /// <param name="ignoreCase">查找时是否忽略父字符串和原子字符串大小写。</param>
  281. /// <returns>替换后的父字符串。</returns>
  282. private static string Replace(string text, string old, string @new, bool ignoreCase = false)
  283. {
  284. if (string.IsNullOrEmpty(text)) return "";
  285. if (string.IsNullOrEmpty(old)) return text;
  286. if (string.IsNullOrEmpty(@new)) return Exlude(text, old, ignoreCase);
  287. if (TextHelper.Len(text) < TextHelper.Len(old)) return text;
  288. if (ignoreCase)
  289. {
  290. try
  291. {
  292. string p = TextHelper.LCase(text);
  293. string o = TextHelper.LCase(old);
  294. int vil = TextHelper.Len(old);
  295. int viv = 1;
  296. int vend = TextHelper.Len(text) - vil + 1;
  297. string vcell;
  298. string vresult = "";
  299. while (viv <= vend)
  300. {
  301. vcell = TextHelper.Middle(p, viv, vil);
  302. if (vcell == o)
  303. {
  304. vresult = vresult + @new;
  305. viv = viv + vil;
  306. }
  307. else
  308. {
  309. vresult = vresult + TextHelper.Middle(text, viv, 1);
  310. viv = viv + 1;
  311. }
  312. }
  313. return vresult;
  314. }
  315. catch { return text; }
  316. }
  317. else
  318. {
  319. try
  320. {
  321. string vresult = text.Replace(old, @new);
  322. return vresult;
  323. }
  324. catch { return ""; }
  325. }
  326. }
  327. /// <summary>修复文本前缀。</summary>
  328. /// <param name="text">原文本。</param>
  329. /// <param name="include">TRUE:追加指定缀;FALSE:去除指定缀。</param>
  330. /// <param name="head">前缀文本。</param>
  331. public static string AssureStarts(string text, string head, bool include = true)
  332. {
  333. if (string.IsNullOrEmpty(text)) return Empty;
  334. if (string.IsNullOrEmpty(head)) return text;
  335. if (include)
  336. {
  337. return text.StartsWith(head) ? text : (head + text);
  338. }
  339. else
  340. {
  341. var headLength = head.Length;
  342. if (!text.StartsWith(head)) return text;
  343. var result = text;
  344. while (true)
  345. {
  346. result = result.Substring(headLength);
  347. if (!result.StartsWith(head)) return result;
  348. }
  349. }
  350. }
  351. /// <summary>修复文本后缀。</summary>
  352. /// <param name="text">原文本。</param>
  353. /// <param name="include">TRUE:追加指定后缀;FALSE:去除指定后缀。</param>
  354. /// <param name="foot">后缀文本。</param>
  355. public static string AssureEnds(string text, string foot, bool include = true)
  356. {
  357. if (string.IsNullOrEmpty(text)) return Empty;
  358. if (string.IsNullOrEmpty(foot)) return text;
  359. if (include == true)
  360. {
  361. return text.EndsWith(foot) ? text : (text + foot);
  362. }
  363. else
  364. {
  365. var footLength = foot.Length;
  366. if (!text.EndsWith(foot)) return text;
  367. var result = text;
  368. while (true)
  369. {
  370. result = result.Substring(0, result.Length - footLength);
  371. if (!result.EndsWith(foot)) return result;
  372. }
  373. }
  374. }
  375. /// <summary>用单字符作为分隔符拆分文本。</summary>
  376. public static string[] Split(string text, char separator)
  377. {
  378. if (text == null) return new string[0];
  379. if (text.Length < 1) return new string[] { "" };
  380. if ((object)separator == null) return new string[] { text };
  381. return text.Split(separator);
  382. }
  383. /// <summary>用字符串作为分隔符拆分文本。</summary>
  384. public static string[] Split(string text, string separator)
  385. {
  386. if (text == null) return new string[0];
  387. if (text.Length < 1) return new string[] { "" };
  388. if (string.IsNullOrEmpty(separator)) return new string[] { text };
  389. if (separator.Length > text.Length) return new string[] { text };
  390. var list = new List<string>();
  391. var position = 0;
  392. var total = text.Length;
  393. var length = separator.Length;
  394. var cell = new StringBuilder();
  395. while (position < total)
  396. {
  397. var read = null as string;
  398. if (position + length < total) read = text.Substring(position, length);
  399. else read = text.Substring(position);
  400. if (read == separator)
  401. {
  402. if (cell.Length > 0)
  403. {
  404. list.Add(cell.ToString());
  405. // cell.Clear();
  406. cell = new StringBuilder();
  407. }
  408. else
  409. {
  410. list.Add("");
  411. }
  412. position += length;
  413. }
  414. else
  415. {
  416. cell.Append((char)text[position]);
  417. position += 1;
  418. }
  419. if (position >= total)
  420. {
  421. list.Add(cell.ToString());
  422. }
  423. }
  424. var array = list.ToArray();
  425. return array;
  426. }
  427. /// <summary>用多个分隔符拆分文本。</summary>
  428. public static string[] Split(string text, params char[] separators)
  429. {
  430. if (text == null) return new string[0];
  431. if (text.Length < 1) return new string[] { "" };
  432. if (separators == null || separators.Length < 1) return new string[] { text };
  433. if (separators.Length == 1) return Split(text, separators[0]);
  434. var list = new List<string>();
  435. var separatorsText = new string(separators);
  436. var sb = new StringBuilder();
  437. foreach (var c in text)
  438. {
  439. if (separatorsText.IndexOf(c) >= 0)
  440. {
  441. list.Add(sb.ToString());
  442. //sb.Clear();
  443. sb = new StringBuilder();
  444. continue;
  445. }
  446. sb.Append(c);
  447. }
  448. list.Add(sb.ToString());
  449. #if !NET20
  450. sb.Clear();
  451. #endif
  452. return list.ToArray();
  453. }
  454. /// <summary>移除字符串前后的空字符。</summary>
  455. /// <param name="text">原始字符串。</param>
  456. /// <param name="trimBlank">移除空格、全角空格、换行符、回车符、制表符和换页符。</param>
  457. public static string Trim(string text, bool trimBlank = false)
  458. {
  459. if (text == null || text == Empty) return Empty;
  460. if (!trimBlank) return Trim(text, ' ');
  461. return Trim(text, BlankChars.ToCharArray());
  462. }
  463. /// <summary>移除字符串前后的指定字符。</summary>
  464. /// <param name="text">原始字符串。</param>
  465. /// <param name="chars">要移除的字符。</param>
  466. public static string Trim(string text, params char[] chars)
  467. {
  468. if (text == null || text == Empty) return Empty;
  469. if (chars == null || chars.Length < 1) return text;
  470. var length = text.Length;
  471. var charsLength = chars.Length;
  472. var starts = 0;
  473. var offset = 0;
  474. while (true)
  475. {
  476. if (offset >= length) break;
  477. var c = text[offset];
  478. var trim = false;
  479. for (var i = 0; i < charsLength; i++)
  480. {
  481. if (c == chars[i])
  482. {
  483. starts += 1;
  484. offset += 1;
  485. trim = true;
  486. break;
  487. }
  488. }
  489. if (trim) continue; else break;
  490. }
  491. var ends = 0;
  492. if (starts < length)
  493. {
  494. offset = length - 1;
  495. while (true)
  496. {
  497. if (offset <= starts) break;
  498. var c = text[offset];
  499. var trim = false;
  500. for (var i = 0; i < charsLength; i++)
  501. {
  502. if (c == chars[i])
  503. {
  504. ends += 1;
  505. offset -= 1;
  506. trim = true;
  507. break;
  508. }
  509. }
  510. if (trim) continue; else break;
  511. }
  512. }
  513. if (starts == 0 && ends == 0) return text;
  514. return text.Substring(starts, length - starts - ends);
  515. }
  516. /// <summary>修剪字符串数组,修剪元素,并去除空字符串。</summary>
  517. public static string[] Trim(this IEnumerable<string> strings)
  518. {
  519. var ab = new ArrayBuilder<string>();
  520. if (strings == null) return ab.Export();
  521. foreach (var str in strings)
  522. {
  523. var trim = Trim(str);
  524. if (string.IsNullOrEmpty(trim)) continue;
  525. ab.Add(trim);
  526. }
  527. var array = ab.Export();
  528. return array;
  529. }
  530. /// <summary>剪取文本内容,若指定头部为空则从原文本首部起,若指定尾部为空则至原文本末尾。</summary>
  531. /// <returns>剪取后的内容,不包含 head 和 foot。</returns>
  532. public static string Cut(string text, string head = null, string foot = null)
  533. {
  534. if (IsEmpty(text)) return Empty;
  535. int start, length;
  536. if (IsEmpty(head))
  537. {
  538. // none
  539. if (IsEmpty(foot)) return Empty;
  540. // foot
  541. length = text.IndexOf(foot);
  542. if (length < 1) return text;
  543. return text.Substring(0, length);
  544. }
  545. else
  546. {
  547. if (IsEmpty(foot))
  548. {
  549. // head
  550. start = text.IndexOf(head);
  551. if (start < 0) return text;
  552. start += head.Length;
  553. return text.Substring(start);
  554. }
  555. // both
  556. start = text.IndexOf(head);
  557. if (start < 0) start = 0;
  558. else start += head.Length;
  559. var temp = start == 0 ? text : text.Substring(start);
  560. length = temp.IndexOf(foot);
  561. if (length < 0) return temp;
  562. if (length == 0) return Empty;
  563. return temp.Substring(0, length);
  564. }
  565. }
  566. /// <summary>比较两个字符串的相似度。返回值大于 0,小于等于 1。</summary>
  567. /// <param name="arg1"></param>
  568. /// <param name="arg2"></param>
  569. /// <returns></returns>
  570. public static double Similarity(string arg1, string arg2) => Levenshtein.Compute(arg1, arg2).Rate;
  571. /// <summary>生成新的 GUID。</summary>
  572. public static string Guid(bool hyphenation = true, bool lower = true)
  573. {
  574. var guid = System.Guid.NewGuid();
  575. var str = hyphenation ? guid.ToString() : guid.ToString("n");
  576. if (!lower) str = str.ToUpper();
  577. return str;
  578. }
  579. /// <summary>生成新主键。</summary>
  580. public static string Key() => System.Guid.NewGuid().ToString("n");
  581. /// <summary>生成随机字符串,出现的字符由字符池指定,默认池包含数字和字母。</summary>
  582. /// <param name="length">随机字符串的长度。</param>
  583. /// <param name="pool">字符池,字符池中每个字符在随机字符串中出现的概率约等。</param>
  584. public static string Random(int length, string pool = "0123456789abcdefghijklmnopqrstuvwxyz")
  585. {
  586. if (length < 1) return Empty;
  587. if (IsEmpty(pool)) return Duplicate(Space, length);
  588. var array = new char[length];
  589. var max = pool.Length - 1;
  590. for (var i = 0; i < length; i++) array[i] = pool[NumberUtility.Random(0, max)];
  591. return new string(array);
  592. }
  593. /// <summary>对字符串集合去重,同时去除 NULL 值和空字符串。</summary>
  594. public static string[] Distinct(this IEnumerable<string> strings) => Distinct(strings, false, false);
  595. /// <summary>对字符串集合去重。</summary>
  596. /// <param name="strings">字符串集合。</param>
  597. /// <param name="withEmpty">保留空字符串。</param>
  598. /// <param name="withNull">保留 NULL 值。</param>
  599. public static string[] Distinct(this IEnumerable<string> strings, bool withEmpty, bool withNull)
  600. {
  601. if (strings == null) return new string[0];
  602. // 保留 NULL 和空字符串
  603. var @null = false;
  604. var empty = false;
  605. // 遍历,重组
  606. var cache = new List<string>();
  607. if (strings is IList<string> list)
  608. {
  609. var count = list.Count;
  610. cache.Capacity = count;
  611. for (var i = 0; i < count; i++)
  612. {
  613. var item = list[i];
  614. if (item == null)
  615. {
  616. if (withNull && !@null)
  617. {
  618. cache.Add(item);
  619. @null = true;
  620. }
  621. continue;
  622. }
  623. if (item == Empty)
  624. {
  625. if (withEmpty && !empty)
  626. {
  627. cache.Add(item);
  628. empty = true;
  629. }
  630. continue;
  631. }
  632. var added = false;
  633. for (var j = 0; j < cache.Count; j++)
  634. {
  635. if (cache[j] == item)
  636. {
  637. added = true;
  638. break;
  639. }
  640. }
  641. if (!added) cache.Add(item);
  642. }
  643. }
  644. else
  645. {
  646. foreach (var item in strings)
  647. {
  648. if (item == null)
  649. {
  650. if (withNull && !@null)
  651. {
  652. cache.Add(item);
  653. @null = true;
  654. }
  655. continue;
  656. }
  657. if (item == Empty)
  658. {
  659. if (withEmpty && !empty)
  660. {
  661. cache.Add(item);
  662. empty = true;
  663. }
  664. continue;
  665. }
  666. var added = false;
  667. for (var j = 0; j < cache.Count; j++)
  668. {
  669. if (cache[j] == item)
  670. {
  671. added = true;
  672. break;
  673. }
  674. }
  675. if (!added) cache.Add(item);
  676. }
  677. }
  678. return cache.ToArray();
  679. }
  680. /// <summary>约束字符串中的字符,只包含指定的字符。</summary>
  681. public static string Restrict(string text, char[] chars)
  682. {
  683. if (IsEmpty(text)) return Empty;
  684. if (chars == null || chars.Length < 1) return Empty;
  685. var total = text.Length;
  686. var count = chars.Length;
  687. var array = new char[total];
  688. var added = 0;
  689. for (var i = 0; i < total; i++)
  690. {
  691. var c = text[i];
  692. for (var j = 0; j < count; j++)
  693. {
  694. if (c == chars[j])
  695. {
  696. array[added] = c;
  697. added += 1;
  698. break;
  699. }
  700. }
  701. }
  702. if (added < 1) return Empty;
  703. return new string(array, 0, added);
  704. }
  705. /// <summary>约束字符串中的字符,只包含指定的字符。</summary>
  706. public static string Restrict(string text, string chars) => IsEmpty(text) || IsEmpty(chars) ? Empty : Restrict(text, chars.ToCharArray());
  707. /// <summary>约束字符串中的字符,只包含字母。</summary>
  708. public static string RestrictLetters(string text) => Restrict(text, LetterChars.ToCharArray());
  709. /// <summary>约束字符串中的字符,只包含数字。</summary>
  710. public static string RestrictNumeric(string text) => Restrict(text, Decimal.ToCharArray());
  711. /// <summary>返回此字符串的安全键副本,只保留数据记录主键中可能出现的字符,默认限制长度为 255 字符。</summary>
  712. public static string SafeKey(string text, int maxLength = 255)
  713. {
  714. if (string.IsNullOrEmpty(text)) return Empty;
  715. var input = text;
  716. var max = maxLength;
  717. if (max < 1 || max > input.Length) max = input.Length;
  718. // 允许用于主键值的字符。
  719. const string KeyCollection = "-_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  720. var sb = new StringBuilder();
  721. var total = input.Length;
  722. var length = 0;
  723. for (var i = 0; i < total; i++)
  724. {
  725. var c = input[i];
  726. if (KeyCollection.IndexOf(c) < 0) continue;
  727. sb.Append(c);
  728. length += 1;
  729. if (length >= max) break;
  730. }
  731. var result = sb.ToString();
  732. if (result.Length > max) result = result.Substring(0, max);
  733. return result;
  734. }
  735. /// <summary>追加字符串。</summary>
  736. public static StringBuilder Append(StringBuilder builder, params object[] cells)
  737. {
  738. if (builder != null) builder.Append(Join(null, cells));
  739. return builder;
  740. }
  741. /// <summary>对 URL 编码。</summary>
  742. public static string EncodeUrl(string plain)
  743. {
  744. return UrlEncoding.Encode(plain);
  745. }
  746. /// <summary>对 URL 解码。</summary>
  747. public static string DecodeUrl(string escaped)
  748. {
  749. return UrlEncoding.Decode(escaped);
  750. }
  751. /// <summary>返回此字符串转换为小写形式的副本。</summary>
  752. public static string Lower(string text)
  753. {
  754. if (text == null) return null;
  755. else if (text.Length < 1) return Empty;
  756. else return text.ToLower();
  757. }
  758. /// <summary>返回此字符串转换为大写形式的副本。</summary>
  759. public static string Upper(string text)
  760. {
  761. if (text == null) return null;
  762. else if (text.Length < 1) return Empty;
  763. else return text.ToUpper();
  764. }
  765. /// <summary>检查中国手机号码,包含 13x、14x、15x、16x、17x、18x 和 19x 号段。</summary>
  766. public static bool IsPhone(string phone)
  767. {
  768. if (string.IsNullOrEmpty(phone)) return false;
  769. var regex = new Regex(@"^(13|14|15|16|17|18|19)\d{9}$", RegexOptions.None);
  770. var match = regex.Match(phone);
  771. return match.Success;
  772. }
  773. /// <summary>渲染 Markdown 文本为 HTML 文本。</summary>
  774. public static string RenderMarkdown(string markdown) => MarkdownSharp.Demo.ToHtml(markdown);
  775. /// <summary>合并用于启动进程的参数。</summary>
  776. public static string MergeProcessArgument(params object[] args)
  777. {
  778. // var special = " \"\n\r\b\t\f";
  779. var list = new List<string>();
  780. if (args != null)
  781. {
  782. foreach (var i in args)
  783. {
  784. var arg = null as string;
  785. if (i != null)
  786. {
  787. if (i is string) arg = i as string;
  788. else arg = i.ToString();
  789. }
  790. if (string.IsNullOrEmpty(arg))
  791. {
  792. list.Add("\"\"");
  793. continue;
  794. }
  795. if (arg.Contains(" ") || arg.Contains("\""))
  796. {
  797. list.Add(Merge("\"", arg.Replace("\"", "\\\""), "\""));
  798. continue;
  799. }
  800. list.Add(arg);
  801. }
  802. }
  803. var result = Join(" ", list.ToArray());
  804. return result;
  805. }
  806. /// <summary>合并用于启动进程的参数。</summary>
  807. private static string MergeProcessArgument_2(params object[] args)
  808. {
  809. if (args == null) return "";
  810. if (args.Length < 1) return "";
  811. var sb = new StringBuilder();
  812. for (var i = 0; i < args.Length; i++)
  813. {
  814. if (i > 0) sb.Append(" ");
  815. var arg = null as string;
  816. if (args[i] != null)
  817. {
  818. if (args[i] is string) arg = args[i] as string;
  819. else arg = args[i].ToString();
  820. }
  821. if (arg.IsEmpty())
  822. {
  823. sb.Append("\"\"");
  824. continue;
  825. }
  826. // var special = " \"\n\r\b\t\f";
  827. var special = " \"";
  828. if (arg.IndexOfAny(special.ToCharArray()) < 0)
  829. {
  830. sb.Append(arg);
  831. }
  832. else
  833. {
  834. sb.Append("\"");
  835. if (arg.NotEmpty())
  836. {
  837. foreach (var c in arg)
  838. {
  839. switch (c)
  840. {
  841. case '"':
  842. sb.Append("\\\"");
  843. break;
  844. // case '\n':
  845. // sb.Append("\\n");
  846. // break;
  847. // case '\r':
  848. // sb.Append("\\r");
  849. // break;
  850. // case '\b':
  851. // sb.Append("\\b");
  852. // break;
  853. // case '\t':
  854. // sb.Append("\\t");
  855. // break;
  856. default:
  857. sb.Append(c);
  858. break;
  859. }
  860. }
  861. }
  862. sb.Append("\"");
  863. }
  864. }
  865. var result = sb.ToString();
  866. return result;
  867. }
  868. /// <summary>字符串仅使用英文。可指定空字符串的返回值。</summary>
  869. public static bool IsEnglish(string text, bool ifEmpty = true)
  870. {
  871. if (string.IsNullOrEmpty(text)) return ifEmpty;
  872. var trim = text.Trim();
  873. if (string.IsNullOrEmpty(trim)) return ifEmpty;
  874. return Regex.IsMatch(trim, "(^[0-9a-zA-Z_ -;:,~!@#%&=<>~\\(\\)\\.\\$\\^\\`\\'\\\"\\&\\{\\}\\[\\]\\|\\*\\+\\?]{0,80}$)");
  875. }
  876. /// <summary>转换文本为驼峰形式,首字小写,其它词首字母大写。</summary>
  877. /// <remarks>示例:toCamelCase</remarks>
  878. public static string Camel(this string text)
  879. {
  880. if (string.IsNullOrEmpty(text) || !char.IsUpper(text[0])) return text;
  881. var chars = text.ToCharArray();
  882. for (int i = 0; i < chars.Length; i++)
  883. {
  884. if (i == 1 && !char.IsUpper(chars[i])) break;
  885. bool hasNext = (i + 1) < chars.Length;
  886. if (i > 0 && hasNext)
  887. {
  888. var nextChar = chars[i + 1];
  889. if (!char.IsUpper(nextChar))
  890. {
  891. if (char.IsSeparator(nextChar)) chars[i] = char.ToLowerInvariant(chars[i]);
  892. break;
  893. }
  894. }
  895. chars[i] = char.ToLowerInvariant(chars[i]);
  896. }
  897. return new string(chars);
  898. }
  899. /// <summary>转换文本为帕斯卡形式,所有词首字母大写。</summary>
  900. /// <remarks>示例:ToPascalCase</remarks>
  901. public static string Pascal(this string text)
  902. {
  903. if (string.IsNullOrEmpty(text)) return text;
  904. var sb = new StringBuilder();
  905. var snake = Snake(text);
  906. var split = snake.Split('_');
  907. foreach (var word in split)
  908. {
  909. if (word.Length < 1) continue;
  910. var chars = word.ToCharArray();
  911. chars[0] = char.ToUpper(chars[0]);
  912. sb.Append(new string(chars));
  913. }
  914. return sb.ToString();
  915. }
  916. /// <summary>转换文本为串式形式,使用横线连接每个词。</summary>
  917. /// <remarks>示例:to-kebab-case</remarks>
  918. public static string Kebab(this string text) => WordCase(text, '-');
  919. /// <summary>转换文本为蛇形形式,使用下划线连接每个词。</summary>
  920. /// <remarks>示例:to_sname_case</remarks>
  921. public static string Snake(this string text) => WordCase(text, '_');
  922. /// <summary>转换单词风格。</summary>
  923. static string WordCase(string text, char separator)
  924. {
  925. if (string.IsNullOrEmpty(text)) return text;
  926. const int StateStart = 1;
  927. const int StateLower = 2;
  928. const int StateUpper = 3;
  929. const int StateNewWord = 4;
  930. var sb = new StringBuilder();
  931. var state = StateStart;
  932. for (int i = 0; i < text.Length; i++)
  933. {
  934. if (text[i] == ' ')
  935. {
  936. if (state != StateStart)
  937. {
  938. state = StateNewWord;
  939. }
  940. }
  941. else if (char.IsUpper(text[i]))
  942. {
  943. switch (state)
  944. {
  945. case StateUpper:
  946. bool hasNext = (i + 1 < text.Length);
  947. if (i > 0 && hasNext)
  948. {
  949. char nextChar = text[i + 1];
  950. if (!char.IsUpper(nextChar) && nextChar != separator)
  951. {
  952. sb.Append(separator);
  953. }
  954. }
  955. break;
  956. case StateLower:
  957. case StateNewWord:
  958. sb.Append(separator);
  959. break;
  960. }
  961. char c;
  962. c = char.ToLower(text[i], CultureInfo.InvariantCulture);
  963. sb.Append(c);
  964. state = StateUpper;
  965. }
  966. else if (text[i] == separator)
  967. {
  968. sb.Append(separator);
  969. state = StateStart;
  970. }
  971. else
  972. {
  973. if (state == StateNewWord) sb.Append(separator);
  974. sb.Append(text[i]);
  975. state = StateLower;
  976. }
  977. }
  978. return sb.ToString();
  979. }
  980. /// <summary>移除参数 chars 中的每一个字符。</summary>
  981. public static string RemoveChars(string text, string chars)
  982. {
  983. if (IsEmpty(text)) return Empty;
  984. if (IsEmpty(chars)) return text;
  985. return RemoveChar(text, chars.ToCharArray());
  986. }
  987. /// <summary>移除指定的一个或多个字符。</summary>
  988. public static string RemoveChar(string text, params char[] chars)
  989. {
  990. if (IsEmpty(text)) return Empty;
  991. if (chars == null || chars.Length < 1) return text;
  992. var length = text.Length;
  993. var array = new char[length];
  994. var count = chars.Length;
  995. var added = 0;
  996. for (var i = 0; i < length; i++)
  997. {
  998. var c = text[i];
  999. var removed = false;
  1000. for (var j = 0; j < count; j++)
  1001. {
  1002. if (c == chars[j])
  1003. {
  1004. removed = true;
  1005. break;
  1006. }
  1007. }
  1008. if (removed) continue;
  1009. array[added] = c;
  1010. added += 1;
  1011. }
  1012. if (added < 1) return Empty;
  1013. return new string(array, 0, added);
  1014. }
  1015. /// <summary>防注入,去除常见的功能符号。可限定字符串长度。</summary>
  1016. public static string AntiInject(string text, int length = -1, string chars = "\"'`\b\f\n\r\t\\/:*?<>|@")
  1017. {
  1018. if (IsEmpty(text) || length == 0) return Empty;
  1019. var t = Trim(text);
  1020. t = RemoveChars(t, chars);
  1021. if (length > 0 && t.Length > length) t = t.Substring(0, length);
  1022. return t;
  1023. }
  1024. /// <summary>获取指定长度的字符串片段,可指定 trim 参数对片段再次修剪。</summary>
  1025. public static string Left(string text, int maxLength, bool trim = false, bool trimBlank = false)
  1026. {
  1027. if (IsEmpty(text)) return Empty;
  1028. if (maxLength > 0 && text.Length > maxLength)
  1029. {
  1030. var left = text.Substring(0, maxLength);
  1031. return trim ? Trim(left, trimBlank) : left;
  1032. }
  1033. else return trim ? Trim(text, trimBlank) : text;
  1034. }
  1035. /// <summary>获取指定长度的字符串片段,可指定 trim 参数对片段再次修剪。</summary>
  1036. public static string Right(string text, int maxLength, bool trim = false, bool trimBlank = false)
  1037. {
  1038. if (IsEmpty(text)) return Empty;
  1039. if (maxLength > 0 && text.Length > maxLength)
  1040. {
  1041. var left = text.Substring(text.Length - maxLength);
  1042. return trim ? Trim(left, trimBlank) : left;
  1043. }
  1044. else return trim ? Trim(text, trimBlank) : text;
  1045. }
  1046. /// <summary>获取字符串片段,起始位置从 0 开始,可指定 trim 参数对片段再次修剪。</summary>
  1047. /// <exception cref="ArgumentOutOfRangeException"></exception>
  1048. public static string Middle(string text, int startIndex, int maxLength = -1, bool trim = false, bool trimBlank = false)
  1049. {
  1050. if (IsEmpty(text) || maxLength == 0) return Empty;
  1051. var total = text.Length;
  1052. var start = startIndex;
  1053. var length = maxLength;
  1054. if (start < 0)
  1055. {
  1056. length = length + start;
  1057. start = 0;
  1058. }
  1059. if (maxLength < 0) length = total;
  1060. if (start + length > total) length = total - start;
  1061. if (start == 0 && length == total) return trim ? Trim(text, trimBlank) : text;
  1062. var middle = text.Substring(start, length);
  1063. return trim ? Trim(middle, trimBlank) : middle;
  1064. }
  1065. #region Lock
  1066. static TextLocker _locker = new TextLocker();
  1067. /// <summary>锁定文本,在锁中执行函数。</summary>
  1068. /// <param name="text">要锁定的文本。</param>
  1069. /// <param name="inLock">要在锁中执行的函数。</param>
  1070. /// <exception cref="ArgumentNullException"></exception>
  1071. public static T Lock<T>(this string text, Func<T> inLock)
  1072. {
  1073. if (inLock == null) throw new ArgumentNullException(nameof(inLock));
  1074. return _locker.InLock(text, inLock);
  1075. }
  1076. /// <summary>锁定文本,在锁中执行函数。</summary>
  1077. /// <param name="text">要锁定的文本。</param>
  1078. /// <param name="inLock">要在锁中执行的函数。</param>
  1079. /// <exception cref="ArgumentNullException"></exception>
  1080. public static void Lock(this string text, Action inLock)
  1081. {
  1082. if (inLock == null) throw new ArgumentNullException(nameof(inLock));
  1083. _locker.InLock(text, inLock);
  1084. }
  1085. #endregion
  1086. #region encoding
  1087. /// <summary>检查字节数组包含 UTF-8 BOM 头。</summary>
  1088. public static bool ContainsBOM(byte[] bytes)
  1089. {
  1090. if (bytes == null) return false;
  1091. if (bytes.LongLength < 3L) return false;
  1092. return bytes[0L] == 0xEF && bytes[1L] == 0xBB && bytes[2L] == 0xBF;
  1093. }
  1094. /// <summary>检查字节数组是 UTF-8 文本。可指定检查的最大字节长度。</summary>
  1095. /// <param name="bytes">要检查的字节数组。</param>
  1096. /// <param name="offset">已检查的偏移量。</param>
  1097. /// <param name="checkLength">检查的最大字节长度。</param>
  1098. public static bool IsUTF8(byte[] bytes, Class<int> offset, int checkLength = 1048576)
  1099. {
  1100. return IsUTF8(bytes, offset, checkLength);
  1101. }
  1102. /// <summary>检查字节数组是 UTF-8 文本,默认最多检测 1MB 数据。</summary>
  1103. /// <param name="bytes">要检查的字节数组。</param>
  1104. /// <param name="checkLength">检查的最大字节长度,指定为 0 将不限制检查长度。</param>
  1105. /// <param name="offset">已检查的偏移量,用于调试。</param>
  1106. public static bool IsUTF8(byte[] bytes, int checkLength = 1048576, Class<int> offset = null)
  1107. {
  1108. // UTF8在Unicode的基础上制定了这样一套规则:
  1109. // 1.对于单字节字符,比特位的最高位为0;
  1110. // 2.对于多字节字符,第一个字节的比特位中,最高位有n个1,剩下的n - 1个字节的比特位中,最高位都是10。
  1111. // 好了,我知道你一定看不懂,那就先来看看下面例子后,再去看上面定义吧。
  1112. // 比如一个字符(“A”),它在UTF8中的编码为(用二进制表示):01000001。由于比特位的最高位是0,表示它是单字节,它只需要1个字节就可以表示。
  1113. // 再比如一个字符(“判”),它在UTF8中的编码为(用二进制表示):11100101 10001000 10100100。由于在第一个字节中,比特位最高位有3个1,说明这个字符总共需要3个字节来表示,且后3 - 1 = 2位字节中,比特位的最高位为10。
  1114. if (bytes == null) return false;
  1115. var length = bytes.LongLength;
  1116. // 检查 BOM 头。
  1117. if (ContainsBOM(bytes)) return true;
  1118. var hasOffset = offset != null;
  1119. var append = 0;
  1120. if (hasOffset) offset.Value = 0;
  1121. for (int i = 0; i < length; i++)
  1122. {
  1123. if (checkLength > 0 && i >= checkLength) break;
  1124. var b = bytes[i];
  1125. if (hasOffset) offset.Value = i;
  1126. // 追加字节最高位为 0。
  1127. if (append > 0)
  1128. {
  1129. if (b >> 6 != 2) return false;
  1130. append -= 1;
  1131. continue;
  1132. }
  1133. // ASCII 字符。
  1134. if (b < 128) continue;
  1135. // 2 字节 UTF-8。
  1136. if (b >= 0xC0 && b <= 0xDF)
  1137. {
  1138. append = 1;
  1139. continue;
  1140. }
  1141. // 3 字节 UTF-8 字符。
  1142. if (b >= 0xE0 && b <= 0xEF)
  1143. {
  1144. append = 2;
  1145. continue;
  1146. }
  1147. // 4 字节 UTF-8 字符。
  1148. if (b >= 0xF0 && b <= 0xF7)
  1149. {
  1150. append = 3;
  1151. continue;
  1152. }
  1153. // 5 字节 UTF-8 字符。
  1154. if (b >= 0xF8 && b <= 0xFB)
  1155. {
  1156. append = 4;
  1157. continue;
  1158. }
  1159. // 6 字节 UTF-8 字符。
  1160. if (b >= 0xFC && b <= 0xFD)
  1161. {
  1162. append = 5;
  1163. continue;
  1164. }
  1165. // 未知字节,非 UTF-8 定义。
  1166. return false;
  1167. }
  1168. return true;
  1169. }
  1170. /// <summary>解析编码名称。</summary>
  1171. /// <returns>解析失败时,返回 NULL 值。</returns>
  1172. private static Encoding ParseEncoding(string encoding)
  1173. {
  1174. if (encoding.IsEmpty()) return null;
  1175. var lower = encoding.Lower();
  1176. var nick = lower.Replace("-", "");
  1177. switch (nick)
  1178. {
  1179. case "ascii":
  1180. return Encoding.ASCII;
  1181. case "bigendia":
  1182. case "bigendianunicode":
  1183. return Encoding.BigEndianUnicode;
  1184. case "utf7":
  1185. return Encoding.UTF7;
  1186. case "utf8":
  1187. return Encoding.UTF8;
  1188. case "utf16":
  1189. case "unicode":
  1190. return Encoding.Unicode;
  1191. case "utf32":
  1192. return Encoding.UTF7;
  1193. case "default":
  1194. return Encoding.Default;
  1195. case "ansi":
  1196. case "gb2312":
  1197. case "gb18030":
  1198. return Encoding.Default;
  1199. }
  1200. return null;
  1201. }
  1202. #endregion
  1203. }
  1204. }