StringExtensions.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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), RegexOptions.IgnoreCase);
  99. }
  100. return Regex.IsMatch(s, string.Join("|", keys));
  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. _ when s.Length >= 11 => Regex.Replace(s, "(.{3}).*(.{4})", $"$1{masks}$2"),
  145. _ when s.Length == 10 => Regex.Replace(s, "(.{3}).*(.{3})", $"$1{masks}$2"),
  146. _ when s.Length == 9 => Regex.Replace(s, "(.{2}).*(.{3})", $"$1{masks}$2"),
  147. _ when s.Length == 8 => Regex.Replace(s, "(.{2}).*(.{2})", $"$1{masks}$2"),
  148. _ when s.Length == 7 => Regex.Replace(s, "(.{1}).*(.{2})", $"$1{masks}$2"),
  149. _ when s.Length == 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. Match 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 query = nslookup.Query(s.Split('@')[1], QueryType.MX).Answers.MxRecords().SelectMany(r => Dns.GetHostAddresses(r.Exchange.Value)).ToList();
  172. isMatch = query.Any(ip => !ip.IsPrivateIP());
  173. }
  174. return (isMatch, match);
  175. }
  176. /// <summary>
  177. /// 邮箱掩码
  178. /// </summary>
  179. /// <param name="s">邮箱</param>
  180. /// <param name="mask">掩码</param>
  181. /// <returns></returns>
  182. public static string MaskEmail(this string s, char mask = '*')
  183. {
  184. return !MatchEmail(s).isMatch ? s : s.Replace(s.Substring(0, s.LastIndexOf("@")), Mask(s.Substring(0, s.LastIndexOf("@")), mask));
  185. }
  186. #endregion Email
  187. #region 匹配完整的URL
  188. /// <summary>
  189. /// 匹配完整格式的URL
  190. /// </summary>
  191. /// <param name="s">源字符串</param>
  192. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  193. /// <returns>匹配对象</returns>
  194. public static Uri MatchUrl(this string s, out bool isMatch)
  195. {
  196. try
  197. {
  198. var uri = new Uri(s);
  199. isMatch = Dns.GetHostAddresses(uri.Host).Any(ip => !ip.IsPrivateIP());
  200. return uri;
  201. }
  202. catch
  203. {
  204. isMatch = false;
  205. return null;
  206. }
  207. }
  208. /// <summary>
  209. /// 匹配完整格式的URL
  210. /// </summary>
  211. /// <param name="s">源字符串</param>
  212. /// <returns>是否匹配成功</returns>
  213. public static bool MatchUrl(this string s)
  214. {
  215. MatchUrl(s, out var isMatch);
  216. return isMatch;
  217. }
  218. #endregion 匹配完整的URL
  219. #region 权威校验身份证号码
  220. /// <summary>
  221. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  222. /// </summary>
  223. /// <param name="s">源字符串</param>
  224. /// <returns>是否匹配成功</returns>
  225. public static bool MatchIdentifyCard(this string s)
  226. {
  227. return s.Length switch
  228. {
  229. 18 => CheckChinaID18(s),
  230. 15 => CheckChinaID15(s),
  231. _ => false
  232. };
  233. }
  234. private static readonly string[] ChinaIDProvinceCodes = {
  235. "11", "12", "13", "14", "15",
  236. "21", "22", "23",
  237. "31", "32", "33", "34", "35", "36", "37",
  238. "41", "42", "43", "44", "45", "46",
  239. "50", "51", "52", "53", "54",
  240. "61", "62", "63", "64", "65",
  241. "71",
  242. "81", "82",
  243. "91"
  244. };
  245. private static bool CheckChinaID18(string ID)
  246. {
  247. ID = ID.ToUpper();
  248. Match m = Regex.Match(ID, @"\d{17}[\dX]", RegexOptions.IgnoreCase);
  249. if (!m.Success)
  250. {
  251. return false;
  252. }
  253. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  254. {
  255. return false;
  256. }
  257. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  258. if (!DateTime.TryParseExact(ID.Substring(6, 8), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  259. {
  260. return false;
  261. }
  262. if (!birthday.In(new DateTime(1800, 1, 1), DateTime.Today))
  263. {
  264. return false;
  265. }
  266. int[] factors = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
  267. int sum = 0;
  268. for (int i = 0; i < 17; i++)
  269. {
  270. sum += (ID[i] - '0') * factors[i];
  271. }
  272. int n = (12 - sum % 11) % 11;
  273. return n < 10 ? ID[17] - '0' == n : ID[17].Equals('X');
  274. }
  275. private static bool CheckChinaID15(string ID)
  276. {
  277. Match m = Regex.Match(ID, @"\d{15}", RegexOptions.IgnoreCase);
  278. if (!m.Success)
  279. {
  280. return false;
  281. }
  282. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  283. {
  284. return false;
  285. }
  286. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  287. if (!DateTime.TryParseExact("19" + ID.Substring(6, 6), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  288. {
  289. return false;
  290. }
  291. return birthday.In(new DateTime(1800, 1, 1), new DateTime(2000, 1, 1));
  292. }
  293. #endregion 权威校验身份证号码
  294. #region IP地址
  295. /// <summary>
  296. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  297. /// </summary>
  298. /// <param name="s">源字符串</param>
  299. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  300. /// <returns>匹配对象</returns>
  301. public static IPAddress MatchInetAddress(this string s, out bool isMatch)
  302. {
  303. isMatch = IPAddress.TryParse(s, out var ip);
  304. return ip;
  305. }
  306. /// <summary>
  307. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  308. /// </summary>
  309. /// <param name="s">源字符串</param>
  310. /// <returns>是否匹配成功</returns>
  311. public static bool MatchInetAddress(this string s)
  312. {
  313. MatchInetAddress(s, out var success);
  314. return success;
  315. }
  316. /// <summary>
  317. /// IP地址转换成数字
  318. /// </summary>
  319. /// <param name="addr">IP地址</param>
  320. /// <returns>数字,输入无效IP地址返回0</returns>
  321. public static uint IPToID(this string addr)
  322. {
  323. if (!IPAddress.TryParse(addr, out var ip))
  324. {
  325. return 0;
  326. }
  327. byte[] bInt = ip.GetAddressBytes();
  328. if (BitConverter.IsLittleEndian)
  329. {
  330. Array.Reverse(bInt);
  331. }
  332. return BitConverter.ToUInt32(bInt, 0);
  333. }
  334. /// <summary>
  335. /// 判断IP是否是私有地址
  336. /// </summary>
  337. /// <param name="ip"></param>
  338. /// <returns></returns>
  339. public static bool IsPrivateIP(this string ip)
  340. {
  341. if (MatchInetAddress(ip))
  342. {
  343. return IPAddress.Parse(ip).IsPrivateIP();
  344. }
  345. return false;
  346. }
  347. /// <summary>
  348. /// 判断IP地址在不在某个IP地址段
  349. /// </summary>
  350. /// <param name="input">需要判断的IP地址</param>
  351. /// <param name="begin">起始地址</param>
  352. /// <param name="ends">结束地址</param>
  353. /// <returns></returns>
  354. public static bool IpAddressInRange(this string input, string begin, string ends)
  355. {
  356. uint current = input.IPToID();
  357. return current >= begin.IPToID() && current <= ends.IPToID();
  358. }
  359. #endregion IP地址
  360. #region 校验手机号码的正确性
  361. /// <summary>
  362. /// 匹配手机号码
  363. /// </summary>
  364. /// <param name="s">源字符串</param>
  365. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  366. /// <returns>匹配对象</returns>
  367. public static Match MatchPhoneNumber(this string s, out bool isMatch)
  368. {
  369. if (string.IsNullOrEmpty(s))
  370. {
  371. isMatch = false;
  372. return null;
  373. }
  374. 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}$");
  375. isMatch = match.Success;
  376. return isMatch ? match : null;
  377. }
  378. /// <summary>
  379. /// 匹配手机号码
  380. /// </summary>
  381. /// <param name="s">源字符串</param>
  382. /// <returns>是否匹配成功</returns>
  383. public static bool MatchPhoneNumber(this string s)
  384. {
  385. MatchPhoneNumber(s, out bool success);
  386. return success;
  387. }
  388. #endregion 校验手机号码的正确性
  389. #region Url
  390. /// <summary>
  391. /// 判断url是否是外部地址
  392. /// </summary>
  393. /// <param name="url"></param>
  394. /// <returns></returns>
  395. public static bool IsExternalAddress(this string url)
  396. {
  397. var uri = new Uri(url);
  398. switch (uri.HostNameType)
  399. {
  400. case UriHostNameType.Dns:
  401. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  402. if (ipHostEntry.AddressList.Where(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork).Any(ipAddress => !ipAddress.IsPrivateIP()))
  403. {
  404. return true;
  405. }
  406. break;
  407. case UriHostNameType.IPv4:
  408. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  409. }
  410. return false;
  411. }
  412. #endregion Url
  413. /// <summary>
  414. /// 转换成字节数组
  415. /// </summary>
  416. /// <param name="this"></param>
  417. /// <returns></returns>
  418. public static byte[] ToByteArray(this string @this)
  419. {
  420. return Activator.CreateInstance<ASCIIEncoding>().GetBytes(@this);
  421. }
  422. #region Crc32
  423. /// <summary>
  424. /// 获取字符串crc32签名
  425. /// </summary>
  426. /// <param name="s"></param>
  427. /// <returns></returns>
  428. public static string Crc32(this string s)
  429. {
  430. return string.Join(string.Empty, new Security.Crc32().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  431. }
  432. /// <summary>
  433. /// 获取字符串crc64签名
  434. /// </summary>
  435. /// <param name="s"></param>
  436. /// <returns></returns>
  437. public static string Crc64(this string s)
  438. {
  439. return string.Join(string.Empty, new Security.Crc64().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  440. }
  441. #endregion Crc32
  442. #region 权威校验中国专利申请号/专利号
  443. /// <summary>
  444. /// 中国专利申请号(授权以后就是专利号)由两种组成
  445. /// 2003年9月30号以前的9位(不带校验位是8号),校验位之前可能还会有一个点,例如:00262311, 002623110 或 00262311.0
  446. /// 2003年10月1号以后的13位(不带校验位是12号),校验位之前可能还会有一个点,例如:200410018477, 2004100184779 或200410018477.9
  447. /// http://www.sipo.gov.cn/docs/pub/old/wxfw/zlwxxxggfw/hlwzljsxt/hlwzljsxtsyzn/201507/P020150713610193194682.pdf
  448. /// 上面的文档中均不包括校验算法,但是下面的校验算法没有问题
  449. /// </summary>
  450. /// <param name="patnum">源字符串</param>
  451. /// <returns>是否匹配成功</returns>
  452. public static bool MatchCNPatentNumber(this string patnum)
  453. {
  454. Regex patnumWithCheckbitPattern = new Regex(@"^
  455. (?<!\d)
  456. (?<patentnum>
  457. (?<basenum>
  458. (?<year>(?<old>8[5-9]|9[0-9]|0[0-3])|(?<new>[2-9]\d{3}))
  459. (?<sn>
  460. (?<patenttype>[12389])
  461. (?(old)\d{5}|(?(new)\d{7}))
  462. )
  463. )
  464. (?:
  465. \.?
  466. (?<checkbit>[0-9X])
  467. )?
  468. )
  469. (?!\d)
  470. $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline);
  471. Match m = patnumWithCheckbitPattern.Match(patnum);
  472. if (!m.Success)
  473. {
  474. return false;
  475. }
  476. bool isPatnumTrue = true;
  477. patnum = patnum.ToUpper().Replace(".", "");
  478. if (patnum.Length == 9 || patnum.Length == 8)
  479. {
  480. byte[] factors8 = new byte[8] { 2, 3, 4, 5, 6, 7, 8, 9 };
  481. int year = Convert.ToUInt16(patnum.Substring(0, 2));
  482. year += (year >= 85) ? (ushort)1900u : (ushort)2000u;
  483. if (year >= 1985 || year <= 2003)
  484. {
  485. int sum = 0;
  486. for (byte i = 0; i < 8; i++)
  487. {
  488. sum += factors8[i] * (patnum[i] - '0');
  489. }
  490. char checkbit = "0123456789X"[sum % 11];
  491. if (patnum.Length == 9)
  492. {
  493. if (checkbit != patnum[8])
  494. {
  495. isPatnumTrue = false;
  496. }
  497. }
  498. else
  499. {
  500. patnum += checkbit;
  501. }
  502. }
  503. else
  504. {
  505. isPatnumTrue = false;
  506. }
  507. }
  508. else if (patnum.Length == 13 || patnum.Length == 12)
  509. {
  510. byte[] factors12 = new byte[12] { 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5 };
  511. int year = Convert.ToUInt16(patnum.Substring(0, 4));
  512. if (year >= 2003 && year <= DateTime.Now.Year)
  513. {
  514. int sum = 0;
  515. for (byte i = 0; i < 12; i++)
  516. {
  517. sum += factors12[i] * (patnum[i] - '0');
  518. }
  519. char checkbit = "0123456789X"[sum % 11];
  520. if (patnum.Length == 13)
  521. {
  522. if (checkbit != patnum[12])
  523. {
  524. isPatnumTrue = false;
  525. }
  526. }
  527. else
  528. {
  529. patnum += checkbit;
  530. }
  531. }
  532. else
  533. {
  534. isPatnumTrue = false;
  535. }
  536. }
  537. else
  538. {
  539. isPatnumTrue = false;
  540. }
  541. return isPatnumTrue;
  542. }
  543. }
  544. #endregion
  545. }