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.

1219 lines
44 KiB

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