StringExtensions.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. using DnsClient;
  2. using Masuit.Tools.DateTimeExt;
  3. using Masuit.Tools.Strings;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Numerics;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. namespace Masuit.Tools
  15. {
  16. public static partial class StringExtensions
  17. {
  18. public static string Join(this IEnumerable<string> strs, string separate = ", ") => string.Join(separate, strs);
  19. /// <summary>
  20. /// 字符串转时间
  21. /// </summary>
  22. /// <param name="value"></param>
  23. /// <returns></returns>
  24. public static DateTime ToDateTime(this string value)
  25. {
  26. DateTime.TryParse(value, out var result);
  27. return result;
  28. }
  29. /// <summary>
  30. /// 字符串转Guid
  31. /// </summary>
  32. /// <param name="s"></param>
  33. /// <returns></returns>
  34. public static Guid ToGuid(this string s)
  35. {
  36. return Guid.Parse(s);
  37. }
  38. /// <summary>
  39. /// 根据正则替换
  40. /// </summary>
  41. /// <param name="input"></param>
  42. /// <param name="regex">正则表达式</param>
  43. /// <param name="replacement">新内容</param>
  44. /// <returns></returns>
  45. public static string Replace(this string input, Regex regex, string replacement)
  46. {
  47. return regex.Replace(input, replacement);
  48. }
  49. /// <summary>
  50. /// 生成唯一短字符串
  51. /// </summary>
  52. /// <param name="str"></param>
  53. /// <param name="chars">可用字符数数量,0-9,a-z,A-Z</param>
  54. /// <returns></returns>
  55. public static string CreateShortToken(this string str, byte chars = 36)
  56. {
  57. var nf = new NumberFormater(chars);
  58. return nf.ToString((DateTime.Now.Ticks - 630822816000000000) * 100 + Stopwatch.GetTimestamp() % 100);
  59. }
  60. /// <summary>
  61. /// 任意进制转十进制
  62. /// </summary>
  63. /// <param name="str"></param>
  64. /// <param name="bin">进制</param>
  65. /// <returns></returns>
  66. public static long FromBinary(this string str, int bin)
  67. {
  68. var nf = new NumberFormater(bin);
  69. return nf.FromString(str);
  70. }
  71. /// <summary>
  72. /// 任意进制转大数十进制
  73. /// </summary>
  74. /// <param name="str"></param>
  75. /// <param name="bin">进制</param>
  76. /// <returns></returns>
  77. public static BigInteger FromBinaryBig(this string str, int bin)
  78. {
  79. var nf = new NumberFormater(bin);
  80. return nf.FromStringBig(str);
  81. }
  82. #region 检测字符串中是否包含列表中的关键词
  83. /// <summary>
  84. /// 检测字符串中是否包含列表中的关键词
  85. /// </summary>
  86. /// <param name="s">源字符串</param>
  87. /// <param name="keys">关键词列表</param>
  88. /// <param name="ignoreCase">忽略大小写</param>
  89. /// <returns></returns>
  90. public static bool Contains(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  91. {
  92. if (!keys.Any() || string.IsNullOrEmpty(s))
  93. {
  94. return false;
  95. }
  96. if (ignoreCase)
  97. {
  98. return Regex.IsMatch(s, string.Join("|", keys.Select(Regex.Escape)), RegexOptions.IgnoreCase);
  99. }
  100. return Regex.IsMatch(s, string.Join("|", keys.Select(Regex.Escape)));
  101. }
  102. /// <summary>
  103. /// 判断是否包含符号
  104. /// </summary>
  105. /// <param name="str"></param>
  106. /// <param name="symbols"></param>
  107. /// <returns></returns>
  108. public static bool ContainsSymbol(this string str, params string[] symbols)
  109. {
  110. return str switch
  111. {
  112. null => false,
  113. string a when string.IsNullOrEmpty(a) => false,
  114. string a when a == string.Empty => false,
  115. _ => symbols.Any(t => str.Contains(t))
  116. };
  117. }
  118. #endregion 检测字符串中是否包含列表中的关键词
  119. /// <summary>
  120. /// 判断字符串是否为空或""
  121. /// </summary>
  122. /// <param name="s"></param>
  123. /// <returns></returns>
  124. public static bool IsNullOrEmpty(this string s)
  125. {
  126. return string.IsNullOrEmpty(s);
  127. }
  128. /// <summary>
  129. /// 字符串掩码
  130. /// </summary>
  131. /// <param name="s">字符串</param>
  132. /// <param name="mask">掩码符</param>
  133. /// <returns></returns>
  134. public static string Mask(this string s, char mask = '*')
  135. {
  136. if (string.IsNullOrWhiteSpace(s?.Trim()))
  137. {
  138. return s;
  139. }
  140. s = s.Trim();
  141. string masks = mask.ToString().PadLeft(4, mask);
  142. return s.Length switch
  143. {
  144. >= 11 => Regex.Replace(s, "(.{3}).*(.{4})", $"$1{masks}$2"),
  145. 10 => Regex.Replace(s, "(.{3}).*(.{3})", $"$1{masks}$2"),
  146. 9 => Regex.Replace(s, "(.{2}).*(.{3})", $"$1{masks}$2"),
  147. 8 => Regex.Replace(s, "(.{2}).*(.{2})", $"$1{masks}$2"),
  148. 7 => Regex.Replace(s, "(.{1}).*(.{2})", $"$1{masks}$2"),
  149. 6 => Regex.Replace(s, "(.{1}).*(.{1})", $"$1{masks}$2"),
  150. _ => Regex.Replace(s, "(.{1}).*", $"$1{masks}")
  151. };
  152. }
  153. #region Email
  154. /// <summary>
  155. /// 匹配Email
  156. /// </summary>
  157. /// <param name="s">源字符串</param>
  158. /// <param name="valid">是否验证有效性</param>
  159. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  160. public static (bool isMatch, Match match) MatchEmail(this string s, bool valid = false)
  161. {
  162. if (string.IsNullOrEmpty(s) || s.Length < 7)
  163. {
  164. return (false, null);
  165. }
  166. var match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  167. var isMatch = match.Success;
  168. if (isMatch && valid)
  169. {
  170. var nslookup = new LookupClient();
  171. var task = nslookup.Query(s.Split('@')[1], QueryType.MX).Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  172. {
  173. if (t.IsCanceled || t.IsFaulted)
  174. {
  175. return new[] { IPAddress.Loopback };
  176. }
  177. return t.Result;
  178. }));
  179. isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  180. }
  181. return (isMatch, match);
  182. }
  183. /// <summary>
  184. /// 邮箱掩码
  185. /// </summary>
  186. /// <param name="s">邮箱</param>
  187. /// <param name="mask">掩码</param>
  188. /// <returns></returns>
  189. public static string MaskEmail(this string s, char mask = '*')
  190. {
  191. var index = s.LastIndexOf("@");
  192. var oldValue = s.Substring(0, index);
  193. return !MatchEmail(s).isMatch ? s : s.Replace(oldValue, Mask(oldValue, mask));
  194. }
  195. #endregion Email
  196. #region 匹配完整的URL
  197. /// <summary>
  198. /// 匹配完整格式的URL
  199. /// </summary>
  200. /// <param name="s">源字符串</param>
  201. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  202. /// <returns>匹配对象</returns>
  203. public static Uri MatchUrl(this string s, out bool isMatch)
  204. {
  205. try
  206. {
  207. var uri = new Uri(s);
  208. isMatch = Dns.GetHostAddresses(uri.Host).Any(ip => !ip.IsPrivateIP());
  209. return uri;
  210. }
  211. catch
  212. {
  213. isMatch = false;
  214. return null;
  215. }
  216. }
  217. /// <summary>
  218. /// 匹配完整格式的URL
  219. /// </summary>
  220. /// <param name="s">源字符串</param>
  221. /// <returns>是否匹配成功</returns>
  222. public static bool MatchUrl(this string s)
  223. {
  224. MatchUrl(s, out var isMatch);
  225. return isMatch;
  226. }
  227. #endregion 匹配完整的URL
  228. #region 权威校验身份证号码
  229. /// <summary>
  230. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  231. /// </summary>
  232. /// <param name="s">源字符串</param>
  233. /// <returns>是否匹配成功</returns>
  234. public static bool MatchIdentifyCard(this string s)
  235. {
  236. return s.Length switch
  237. {
  238. 18 => CheckChinaID18(s),
  239. 15 => CheckChinaID15(s),
  240. _ => false
  241. };
  242. }
  243. private static readonly string[] ChinaIDProvinceCodes = {
  244. "11", "12", "13", "14", "15",
  245. "21", "22", "23",
  246. "31", "32", "33", "34", "35", "36", "37",
  247. "41", "42", "43", "44", "45", "46",
  248. "50", "51", "52", "53", "54",
  249. "61", "62", "63", "64", "65",
  250. "71",
  251. "81", "82",
  252. "91"
  253. };
  254. private static bool CheckChinaID18(string ID)
  255. {
  256. ID = ID.ToUpper();
  257. Match m = Regex.Match(ID, @"\d{17}[\dX]", RegexOptions.IgnoreCase);
  258. if (!m.Success)
  259. {
  260. return false;
  261. }
  262. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  263. {
  264. return false;
  265. }
  266. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  267. if (!DateTime.TryParseExact(ID.Substring(6, 8), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  268. {
  269. return false;
  270. }
  271. if (!birthday.In(new DateTime(1800, 1, 1), DateTime.Today))
  272. {
  273. return false;
  274. }
  275. int[] factors = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
  276. int sum = 0;
  277. for (int i = 0; i < 17; i++)
  278. {
  279. sum += (ID[i] - '0') * factors[i];
  280. }
  281. int n = (12 - sum % 11) % 11;
  282. return n < 10 ? ID[17] - '0' == n : ID[17].Equals('X');
  283. }
  284. private static bool CheckChinaID15(string ID)
  285. {
  286. Match m = Regex.Match(ID, @"\d{15}", RegexOptions.IgnoreCase);
  287. if (!m.Success)
  288. {
  289. return false;
  290. }
  291. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  292. {
  293. return false;
  294. }
  295. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  296. if (!DateTime.TryParseExact("19" + ID.Substring(6, 6), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  297. {
  298. return false;
  299. }
  300. return birthday.In(new DateTime(1800, 1, 1), new DateTime(2000, 1, 1));
  301. }
  302. #endregion 权威校验身份证号码
  303. #region IP地址
  304. /// <summary>
  305. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  306. /// </summary>
  307. /// <param name="s">源字符串</param>
  308. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  309. /// <returns>匹配对象</returns>
  310. public static IPAddress MatchInetAddress(this string s, out bool isMatch)
  311. {
  312. isMatch = IPAddress.TryParse(s, out var ip);
  313. return ip;
  314. }
  315. /// <summary>
  316. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  317. /// </summary>
  318. /// <param name="s">源字符串</param>
  319. /// <returns>是否匹配成功</returns>
  320. public static bool MatchInetAddress(this string s)
  321. {
  322. MatchInetAddress(s, out var success);
  323. return success;
  324. }
  325. /// <summary>
  326. /// IP地址转换成数字
  327. /// </summary>
  328. /// <param name="addr">IP地址</param>
  329. /// <returns>数字,输入无效IP地址返回0</returns>
  330. public static uint IPToID(this string addr)
  331. {
  332. if (!IPAddress.TryParse(addr, out var ip))
  333. {
  334. return 0;
  335. }
  336. byte[] bInt = ip.GetAddressBytes();
  337. if (BitConverter.IsLittleEndian)
  338. {
  339. Array.Reverse(bInt);
  340. }
  341. return BitConverter.ToUInt32(bInt, 0);
  342. }
  343. /// <summary>
  344. /// 判断IP是否是私有地址
  345. /// </summary>
  346. /// <param name="ip"></param>
  347. /// <returns></returns>
  348. public static bool IsPrivateIP(this string ip)
  349. {
  350. if (MatchInetAddress(ip))
  351. {
  352. return IPAddress.Parse(ip).IsPrivateIP();
  353. }
  354. return false;
  355. }
  356. /// <summary>
  357. /// 判断IP地址在不在某个IP地址段
  358. /// </summary>
  359. /// <param name="input">需要判断的IP地址</param>
  360. /// <param name="begin">起始地址</param>
  361. /// <param name="ends">结束地址</param>
  362. /// <returns></returns>
  363. public static bool IpAddressInRange(this string input, string begin, string ends)
  364. {
  365. uint current = input.IPToID();
  366. return current >= begin.IPToID() && current <= ends.IPToID();
  367. }
  368. #endregion IP地址
  369. #region 校验手机号码的正确性
  370. /// <summary>
  371. /// 匹配手机号码
  372. /// </summary>
  373. /// <param name="s">源字符串</param>
  374. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  375. /// <returns>匹配对象</returns>
  376. public static Match MatchPhoneNumber(this string s, out bool isMatch)
  377. {
  378. if (string.IsNullOrEmpty(s))
  379. {
  380. isMatch = false;
  381. return null;
  382. }
  383. Match match = Regex.Match(s, @"^((1[3,5,6,8][0-9])|(14[5,7])|(17[0,1,3,6,7,8])|(19[8,9]))\d{8}$");
  384. isMatch = match.Success;
  385. return isMatch ? match : null;
  386. }
  387. /// <summary>
  388. /// 匹配手机号码
  389. /// </summary>
  390. /// <param name="s">源字符串</param>
  391. /// <returns>是否匹配成功</returns>
  392. public static bool MatchPhoneNumber(this string s)
  393. {
  394. MatchPhoneNumber(s, out bool success);
  395. return success;
  396. }
  397. #endregion 校验手机号码的正确性
  398. #region Url
  399. /// <summary>
  400. /// 判断url是否是外部地址
  401. /// </summary>
  402. /// <param name="url"></param>
  403. /// <returns></returns>
  404. public static bool IsExternalAddress(this string url)
  405. {
  406. var uri = new Uri(url);
  407. switch (uri.HostNameType)
  408. {
  409. case UriHostNameType.Dns:
  410. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  411. if (ipHostEntry.AddressList.Where(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork).Any(ipAddress => !ipAddress.IsPrivateIP()))
  412. {
  413. return true;
  414. }
  415. break;
  416. case UriHostNameType.IPv4:
  417. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  418. }
  419. return false;
  420. }
  421. #endregion Url
  422. /// <summary>
  423. /// 转换成字节数组
  424. /// </summary>
  425. /// <param name="this"></param>
  426. /// <returns></returns>
  427. public static byte[] ToByteArray(this string @this)
  428. {
  429. return Encoding.ASCII.GetBytes(@this);
  430. }
  431. #region Crc32
  432. /// <summary>
  433. /// 获取字符串crc32签名
  434. /// </summary>
  435. /// <param name="s"></param>
  436. /// <returns></returns>
  437. public static string Crc32(this string s)
  438. {
  439. return string.Join(string.Empty, new Security.Crc32().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  440. }
  441. /// <summary>
  442. /// 获取字符串crc64签名
  443. /// </summary>
  444. /// <param name="s"></param>
  445. /// <returns></returns>
  446. public static string Crc64(this string s)
  447. {
  448. return string.Join(string.Empty, new Security.Crc64().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  449. }
  450. #endregion Crc32
  451. #region 权威校验中国专利申请号/专利号
  452. /// <summary>
  453. /// 中国专利申请号(授权以后就是专利号)由两种组成
  454. /// 2003年9月30号以前的9位(不带校验位是8号),校验位之前可能还会有一个点,例如:00262311, 002623110 或 00262311.0
  455. /// 2003年10月1号以后的13位(不带校验位是12号),校验位之前可能还会有一个点,例如:200410018477, 2004100184779 或200410018477.9
  456. /// http://www.sipo.gov.cn/docs/pub/old/wxfw/zlwxxxggfw/hlwzljsxt/hlwzljsxtsyzn/201507/P020150713610193194682.pdf
  457. /// 上面的文档中均不包括校验算法,但是下面的校验算法没有问题
  458. /// </summary>
  459. /// <param name="patnum">源字符串</param>
  460. /// <returns>是否匹配成功</returns>
  461. public static bool MatchCNPatentNumber(this string patnum)
  462. {
  463. Regex patnumWithCheckbitPattern = new Regex(@"^
  464. (?<!\d)
  465. (?<patentnum>
  466. (?<basenum>
  467. (?<year>(?<old>8[5-9]|9[0-9]|0[0-3])|(?<new>[2-9]\d{3}))
  468. (?<sn>
  469. (?<patenttype>[12389])
  470. (?(old)\d{5}|(?(new)\d{7}))
  471. )
  472. )
  473. (?:
  474. \.?
  475. (?<checkbit>[0-9X])
  476. )?
  477. )
  478. (?!\d)
  479. $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline);
  480. Match m = patnumWithCheckbitPattern.Match(patnum);
  481. if (!m.Success)
  482. {
  483. return false;
  484. }
  485. bool isPatnumTrue = true;
  486. patnum = patnum.ToUpper().Replace(".", "");
  487. if (patnum.Length == 9 || patnum.Length == 8)
  488. {
  489. byte[] factors8 = new byte[8] { 2, 3, 4, 5, 6, 7, 8, 9 };
  490. int year = Convert.ToUInt16(patnum.Substring(0, 2));
  491. year += (year >= 85) ? (ushort)1900u : (ushort)2000u;
  492. if (year >= 1985 || year <= 2003)
  493. {
  494. int sum = 0;
  495. for (byte i = 0; i < 8; i++)
  496. {
  497. sum += factors8[i] * (patnum[i] - '0');
  498. }
  499. char checkbit = "0123456789X"[sum % 11];
  500. if (patnum.Length == 9)
  501. {
  502. if (checkbit != patnum[8])
  503. {
  504. isPatnumTrue = false;
  505. }
  506. }
  507. else
  508. {
  509. patnum += checkbit;
  510. }
  511. }
  512. else
  513. {
  514. isPatnumTrue = false;
  515. }
  516. }
  517. else if (patnum.Length == 13 || patnum.Length == 12)
  518. {
  519. byte[] factors12 = new byte[12] { 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5 };
  520. int year = Convert.ToUInt16(patnum.Substring(0, 4));
  521. if (year >= 2003 && year <= DateTime.Now.Year)
  522. {
  523. int sum = 0;
  524. for (byte i = 0; i < 12; i++)
  525. {
  526. sum += factors12[i] * (patnum[i] - '0');
  527. }
  528. char checkbit = "0123456789X"[sum % 11];
  529. if (patnum.Length == 13)
  530. {
  531. if (checkbit != patnum[12])
  532. {
  533. isPatnumTrue = false;
  534. }
  535. }
  536. else
  537. {
  538. patnum += checkbit;
  539. }
  540. }
  541. else
  542. {
  543. isPatnumTrue = false;
  544. }
  545. }
  546. else
  547. {
  548. isPatnumTrue = false;
  549. }
  550. return isPatnumTrue;
  551. }
  552. }
  553. #endregion
  554. }