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.

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