StringExtensions.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace Masuit.Tools
  17. {
  18. public static partial class StringExtensions
  19. {
  20. public static string Join(this IEnumerable<string> strs, string separate = ", ", bool removeEmptyEntry = false) => string.Join(separate, removeEmptyEntry ? strs.Where(s => !string.IsNullOrEmpty(s)) : strs);
  21. public static string Join<T>(this IEnumerable<T> strs, string separate = ", ", bool removeEmptyEntry = false) => string.Join(separate, removeEmptyEntry ? strs.Where(t => t != null) : strs);
  22. /// <summary>
  23. /// 字符串转时间
  24. /// </summary>
  25. /// <param name="value"></param>
  26. /// <returns></returns>
  27. public static DateTime ToDateTime(this string value)
  28. {
  29. DateTime.TryParse(value, out var result);
  30. return result;
  31. }
  32. /// <summary>
  33. /// 字符串转Guid
  34. /// </summary>
  35. /// <param name="s"></param>
  36. /// <returns></returns>
  37. public static Guid ToGuid(this string s)
  38. {
  39. return Guid.Parse(s);
  40. }
  41. /// <summary>
  42. /// 根据正则替换
  43. /// </summary>
  44. /// <param name="input"></param>
  45. /// <param name="regex">正则表达式</param>
  46. /// <param name="replacement">新内容</param>
  47. /// <returns></returns>
  48. public static string Replace(this string input, Regex regex, string replacement)
  49. {
  50. return regex.Replace(input, replacement);
  51. }
  52. /// <summary>
  53. /// 生成唯一短字符串
  54. /// </summary>
  55. /// <param name="str"></param>
  56. /// <param name="chars">可用字符数数量,0-9,a-z,A-Z</param>
  57. /// <returns></returns>
  58. public static string CreateShortToken(this string str, byte chars = 36)
  59. {
  60. var nf = new NumberFormater(chars);
  61. return nf.ToString((DateTime.Now.Ticks - 630822816000000000) * 100 + Stopwatch.GetTimestamp() % 100);
  62. }
  63. /// <summary>
  64. /// 任意进制转十进制
  65. /// </summary>
  66. /// <param name="str"></param>
  67. /// <param name="base">进制</param>
  68. /// <returns></returns>
  69. public static long FromBase(this string str, byte @base)
  70. {
  71. var nf = new NumberFormater(@base);
  72. return nf.FromString(str);
  73. }
  74. /// <summary>
  75. /// 任意进制转大数十进制
  76. /// </summary>
  77. /// <param name="str"></param>
  78. /// <param name="base">进制</param>
  79. /// <returns></returns>
  80. public static BigInteger FromBaseBig(this string str, byte @base)
  81. {
  82. var nf = new NumberFormater(@base);
  83. return nf.FromStringBig(str);
  84. }
  85. #region 检测字符串中是否包含列表中的关键词
  86. /// <summary>
  87. /// 检测字符串中是否包含列表中的关键词(快速匹配)
  88. /// </summary>
  89. /// <param name="s">源字符串</param>
  90. /// <param name="keys">关键词列表</param>
  91. /// <param name="ignoreCase">忽略大小写</param>
  92. /// <returns></returns>
  93. public static bool Contains(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  94. {
  95. if (keys is not ICollection<string> array)
  96. {
  97. array = keys.ToArray();
  98. }
  99. if (array.Count == 0 || string.IsNullOrEmpty(s))
  100. {
  101. return false;
  102. }
  103. return ignoreCase ? array.Any(item => s.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0) : array.Any(s.Contains);
  104. }
  105. /// <summary>
  106. /// 检测字符串中是否包含列表中的关键词(安全匹配)
  107. /// </summary>
  108. /// <param name="s">源字符串</param>
  109. /// <param name="keys">关键词列表</param>
  110. /// <param name="ignoreCase">忽略大小写</param>
  111. /// <returns></returns>
  112. public static bool ContainsSafety(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  113. {
  114. if (keys is not ICollection<string> array)
  115. {
  116. array = keys.ToArray();
  117. }
  118. if (array.Count == 0 || string.IsNullOrEmpty(s))
  119. {
  120. return false;
  121. }
  122. bool flag = false;
  123. if (ignoreCase)
  124. {
  125. foreach (var item in array)
  126. {
  127. if (s.Contains(item))
  128. {
  129. flag = true;
  130. }
  131. }
  132. }
  133. else
  134. {
  135. foreach (var item in array)
  136. {
  137. if (s.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0)
  138. {
  139. flag = true;
  140. }
  141. }
  142. }
  143. return flag;
  144. }
  145. /// <summary>
  146. /// 检测字符串中是否以列表中的关键词结尾
  147. /// </summary>
  148. /// <param name="s">源字符串</param>
  149. /// <param name="keys">关键词列表</param>
  150. /// <param name="ignoreCase">忽略大小写</param>
  151. /// <returns></returns>
  152. public static bool EndsWith(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  153. {
  154. if (keys is not ICollection<string> array)
  155. {
  156. array = keys.ToArray();
  157. }
  158. if (array.Count == 0 || string.IsNullOrEmpty(s))
  159. {
  160. return false;
  161. }
  162. var pattern = $"({array.Select(Regex.Escape).Join("|")})$";
  163. return ignoreCase ? Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase) : Regex.IsMatch(s, pattern);
  164. }
  165. /// <summary>
  166. /// 检测字符串中是否以列表中的关键词开始
  167. /// </summary>
  168. /// <param name="s">源字符串</param>
  169. /// <param name="keys">关键词列表</param>
  170. /// <param name="ignoreCase">忽略大小写</param>
  171. /// <returns></returns>
  172. public static bool StartsWith(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  173. {
  174. if (keys is not ICollection<string> array)
  175. {
  176. array = keys.ToArray();
  177. }
  178. if (array.Count == 0 || string.IsNullOrEmpty(s))
  179. {
  180. return false;
  181. }
  182. var pattern = $"^({array.Select(Regex.Escape).Join("|")})";
  183. return ignoreCase ? Regex.IsMatch(s, pattern, RegexOptions.IgnoreCase) : Regex.IsMatch(s, pattern);
  184. }
  185. /// <summary>
  186. /// 检测字符串中是否包含列表中的关键词
  187. /// </summary>
  188. /// <param name="s">源字符串</param>
  189. /// <param name="regex">关键词列表</param>
  190. /// <param name="ignoreCase">忽略大小写</param>
  191. /// <returns></returns>
  192. public static bool RegexMatch(this string s, string regex, bool ignoreCase = true)
  193. {
  194. if (string.IsNullOrEmpty(regex) || string.IsNullOrEmpty(s))
  195. {
  196. return false;
  197. }
  198. if (ignoreCase)
  199. {
  200. return Regex.IsMatch(s, regex, RegexOptions.IgnoreCase);
  201. }
  202. return Regex.IsMatch(s, regex);
  203. }
  204. /// <summary>
  205. /// 检测字符串中是否包含列表中的关键词
  206. /// </summary>
  207. /// <param name="s">源字符串</param>
  208. /// <param name="regex">关键词列表</param>
  209. /// <returns></returns>
  210. public static bool RegexMatch(this string s, Regex regex) => !string.IsNullOrEmpty(s) && regex.IsMatch(s);
  211. #endregion 检测字符串中是否包含列表中的关键词
  212. /// <summary>
  213. /// 判断字符串是否为空或""
  214. /// </summary>
  215. /// <param name="s"></param>
  216. /// <returns></returns>
  217. public static bool IsNullOrEmpty(this string s)
  218. {
  219. return string.IsNullOrWhiteSpace(s) || s.Equals("null", StringComparison.CurrentCultureIgnoreCase);
  220. }
  221. /// <summary>
  222. /// 转成非null
  223. /// </summary>
  224. /// <param name="s"></param>
  225. /// <returns></returns>
  226. public static string AsNotNull(this string s)
  227. {
  228. return string.IsNullOrEmpty(s) ? "" : s;
  229. }
  230. /// <summary>
  231. /// 转成非null
  232. /// </summary>
  233. /// <param name="s"></param>
  234. /// <param name="value">为空时的替换值</param>
  235. /// <returns></returns>
  236. public static string IfNullOrEmpty(this string s, string value)
  237. {
  238. return string.IsNullOrEmpty(s) ? value : s;
  239. }
  240. /// <summary>
  241. /// 转成非null
  242. /// </summary>
  243. /// <param name="s"></param>
  244. /// <param name="valueFactory">为空时的替换值函数</param>
  245. /// <returns></returns>
  246. public static string IfNullOrEmpty(this string s, Func<string> valueFactory)
  247. {
  248. return string.IsNullOrEmpty(s) ? valueFactory() : s;
  249. }
  250. /// <summary>
  251. /// 字符串掩码
  252. /// </summary>
  253. /// <param name="s">字符串</param>
  254. /// <param name="mask">掩码符</param>
  255. /// <returns></returns>
  256. public static string Mask(this string s, char mask = '*')
  257. {
  258. if (string.IsNullOrWhiteSpace(s?.Trim()))
  259. {
  260. return s;
  261. }
  262. s = s.Trim();
  263. string masks = mask.ToString().PadLeft(4, mask);
  264. return s.Length switch
  265. {
  266. >= 11 => Regex.Replace(s, "(.{3}).*(.{4})", $"$1{masks}$2"),
  267. 10 => Regex.Replace(s, "(.{3}).*(.{3})", $"$1{masks}$2"),
  268. 9 => Regex.Replace(s, "(.{2}).*(.{3})", $"$1{masks}$2"),
  269. 8 => Regex.Replace(s, "(.{2}).*(.{2})", $"$1{masks}$2"),
  270. 7 => Regex.Replace(s, "(.{1}).*(.{2})", $"$1{masks}$2"),
  271. 6 => Regex.Replace(s, "(.{1}).*(.{1})", $"$1{masks}$2"),
  272. _ => Regex.Replace(s, "(.{1}).*", $"$1{masks}")
  273. };
  274. }
  275. #region Email
  276. /// <summary>
  277. /// 匹配Email
  278. /// </summary>
  279. /// <param name="s">源字符串</param>
  280. /// <param name="valid">是否验证有效性</param>
  281. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  282. public static (bool isMatch, Match match) MatchEmail(this string s, bool valid = false)
  283. {
  284. if (string.IsNullOrEmpty(s) || s.Length < 7)
  285. {
  286. return (false, null);
  287. }
  288. var match = Regex.Match(s, @"[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+");
  289. var isMatch = match.Success;
  290. if (isMatch && valid)
  291. {
  292. var nslookup = new LookupClient();
  293. var task = nslookup.Query(s.Split('@')[1], QueryType.MX).Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  294. {
  295. if (t.IsCanceled || t.IsFaulted)
  296. {
  297. return new[] { IPAddress.Loopback };
  298. }
  299. return t.Result;
  300. }));
  301. isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  302. }
  303. return (isMatch, match);
  304. }
  305. /// <summary>
  306. /// 匹配Email
  307. /// </summary>
  308. /// <param name="s">源字符串</param>
  309. /// <param name="valid">是否验证有效性</param>
  310. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  311. public static async Task<(bool isMatch, Match match)> MatchEmailAsync(this string s, bool valid = false)
  312. {
  313. if (string.IsNullOrEmpty(s) || s.Length < 7)
  314. {
  315. return (false, null);
  316. }
  317. var match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  318. var isMatch = match.Success;
  319. if (isMatch && valid)
  320. {
  321. var nslookup = new LookupClient();
  322. using var cts = new CancellationTokenSource(100);
  323. var query = await nslookup.QueryAsync(s.Split('@')[1], QueryType.MX, cancellationToken: cts.Token);
  324. var result = await query.Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  325. {
  326. if (t.IsCanceled || t.IsFaulted)
  327. {
  328. return new[] { IPAddress.Loopback };
  329. }
  330. return t.Result;
  331. }));
  332. isMatch = result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  333. }
  334. return (isMatch, match);
  335. }
  336. /// <summary>
  337. /// 邮箱掩码
  338. /// </summary>
  339. /// <param name="s">邮箱</param>
  340. /// <param name="mask">掩码</param>
  341. /// <returns></returns>
  342. public static string MaskEmail(this string s, char mask = '*')
  343. {
  344. var index = s.LastIndexOf("@");
  345. var oldValue = s.Substring(0, index);
  346. return !MatchEmail(s).isMatch ? s : s.Replace(oldValue, Mask(oldValue, mask));
  347. }
  348. #endregion Email
  349. #region 匹配完整的URL
  350. /// <summary>
  351. /// 匹配完整格式的URL
  352. /// </summary>
  353. /// <param name="s">源字符串</param>
  354. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  355. /// <returns>匹配对象</returns>
  356. public static Uri MatchUrl(this string s, out bool isMatch)
  357. {
  358. try
  359. {
  360. var uri = new Uri(s);
  361. isMatch = Dns.GetHostAddresses(uri.Host).Any(ip => !ip.IsPrivateIP());
  362. return uri;
  363. }
  364. catch
  365. {
  366. isMatch = false;
  367. return null;
  368. }
  369. }
  370. /// <summary>
  371. /// 匹配完整格式的URL
  372. /// </summary>
  373. /// <param name="s">源字符串</param>
  374. /// <returns>是否匹配成功</returns>
  375. public static bool MatchUrl(this string s)
  376. {
  377. MatchUrl(s, out var isMatch);
  378. return isMatch;
  379. }
  380. #endregion 匹配完整的URL
  381. #region 权威校验身份证号码
  382. /// <summary>
  383. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  384. /// </summary>
  385. /// <param name="s">源字符串</param>
  386. /// <returns>是否匹配成功</returns>
  387. public static bool MatchIdentifyCard(this string s)
  388. {
  389. return s.Length switch
  390. {
  391. 18 => CheckChinaID18(s),
  392. 15 => CheckChinaID15(s),
  393. _ => false
  394. };
  395. }
  396. private static readonly string[] ChinaIDProvinceCodes = {
  397. "11", "12", "13", "14", "15",
  398. "21", "22", "23",
  399. "31", "32", "33", "34", "35", "36", "37",
  400. "41", "42", "43", "44", "45", "46",
  401. "50", "51", "52", "53", "54",
  402. "61", "62", "63", "64", "65",
  403. "71",
  404. "81", "82",
  405. "91"
  406. };
  407. private static bool CheckChinaID18(string ID)
  408. {
  409. ID = ID.ToUpper();
  410. Match m = Regex.Match(ID, @"\d{17}[\dX]", RegexOptions.IgnoreCase);
  411. if (!m.Success)
  412. {
  413. return false;
  414. }
  415. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  416. {
  417. return false;
  418. }
  419. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  420. if (!DateTime.TryParseExact(ID.Substring(6, 8), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  421. {
  422. return false;
  423. }
  424. if (!birthday.In(new DateTime(1800, 1, 1), DateTime.Today))
  425. {
  426. return false;
  427. }
  428. int[] factors = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
  429. int sum = 0;
  430. for (int i = 0; i < 17; i++)
  431. {
  432. sum += (ID[i] - '0') * factors[i];
  433. }
  434. int n = (12 - sum % 11) % 11;
  435. return n < 10 ? ID[17] - '0' == n : ID[17].Equals('X');
  436. }
  437. private static bool CheckChinaID15(string ID)
  438. {
  439. Match m = Regex.Match(ID, @"\d{15}", RegexOptions.IgnoreCase);
  440. if (!m.Success)
  441. {
  442. return false;
  443. }
  444. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  445. {
  446. return false;
  447. }
  448. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  449. if (!DateTime.TryParseExact("19" + ID.Substring(6, 6), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  450. {
  451. return false;
  452. }
  453. return birthday.In(new DateTime(1800, 1, 1), new DateTime(2000, 1, 1));
  454. }
  455. #endregion 权威校验身份证号码
  456. #region IP地址
  457. /// <summary>
  458. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  459. /// </summary>
  460. /// <param name="s">源字符串</param>
  461. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  462. /// <returns>匹配对象</returns>
  463. public static IPAddress MatchInetAddress(this string s, out bool isMatch)
  464. {
  465. isMatch = IPAddress.TryParse(s, out var ip);
  466. return ip;
  467. }
  468. /// <summary>
  469. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  470. /// </summary>
  471. /// <param name="s">源字符串</param>
  472. /// <returns>是否匹配成功</returns>
  473. public static bool MatchInetAddress(this string s)
  474. {
  475. MatchInetAddress(s, out var success);
  476. return success;
  477. }
  478. /// <summary>
  479. /// IP地址转换成数字
  480. /// </summary>
  481. /// <param name="addr">IP地址</param>
  482. /// <returns>数字,输入无效IP地址返回0</returns>
  483. public static uint IPToID(this string addr)
  484. {
  485. if (!IPAddress.TryParse(addr, out var ip))
  486. {
  487. return 0;
  488. }
  489. byte[] bInt = ip.GetAddressBytes();
  490. if (BitConverter.IsLittleEndian)
  491. {
  492. Array.Reverse(bInt);
  493. }
  494. return BitConverter.ToUInt32(bInt, 0);
  495. }
  496. /// <summary>
  497. /// IP地址转换成数字
  498. /// </summary>
  499. /// <param name="ip">IP地址</param>
  500. /// <returns>数字,输入无效IP地址返回0</returns>
  501. public static uint ToUInt32(this IPAddress ip)
  502. {
  503. byte[] bInt = ip.GetAddressBytes();
  504. if (BitConverter.IsLittleEndian)
  505. {
  506. Array.Reverse(bInt);
  507. }
  508. return BitConverter.ToUInt32(bInt, 0);
  509. }
  510. /// <summary>
  511. /// 判断IP是否是私有地址
  512. /// </summary>
  513. /// <param name="ip"></param>
  514. /// <returns></returns>
  515. public static bool IsPrivateIP(this string ip)
  516. {
  517. var address = MatchInetAddress(ip, out var b);
  518. return b && address.IsPrivateIP();
  519. }
  520. /// <summary>
  521. /// 判断IP地址在不在某个IP地址段
  522. /// </summary>
  523. /// <param name="input">需要判断的IP地址</param>
  524. /// <param name="begin">起始地址</param>
  525. /// <param name="ends">结束地址</param>
  526. /// <returns></returns>
  527. public static bool IpAddressInRange(this string input, string begin, string ends)
  528. {
  529. uint current = input.IPToID();
  530. return current >= begin.IPToID() && current <= ends.IPToID();
  531. }
  532. /// <summary>
  533. /// 判断IP地址在不在某个IP地址段
  534. /// </summary>
  535. /// <param name="input">需要判断的IP地址</param>
  536. /// <param name="begin">起始地址</param>
  537. /// <param name="ends">结束地址</param>
  538. /// <returns></returns>
  539. public static bool IpAddressInRange(this IPAddress input, IPAddress begin, IPAddress ends)
  540. {
  541. uint current = input.ToUInt32();
  542. return current >= begin.ToUInt32() && current <= ends.ToUInt32();
  543. }
  544. #endregion IP地址
  545. #region 校验手机号码的正确性
  546. /// <summary>
  547. /// 匹配手机号码
  548. /// </summary>
  549. /// <param name="s">源字符串</param>
  550. /// <returns>是否匹配成功</returns>
  551. public static bool MatchPhoneNumber(this string s)
  552. {
  553. return !string.IsNullOrEmpty(s) && s[0] == '1' && (s[1] > '2' || s[1] <= '9');
  554. }
  555. #endregion 校验手机号码的正确性
  556. #region Url
  557. /// <summary>
  558. /// 判断url是否是外部地址
  559. /// </summary>
  560. /// <param name="url"></param>
  561. /// <returns></returns>
  562. public static bool IsExternalAddress(this string url)
  563. {
  564. var uri = new Uri(url);
  565. switch (uri.HostNameType)
  566. {
  567. case UriHostNameType.Dns:
  568. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  569. if (ipHostEntry.AddressList.Where(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork).Any(ipAddress => !ipAddress.IsPrivateIP()))
  570. {
  571. return true;
  572. }
  573. break;
  574. case UriHostNameType.IPv4:
  575. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  576. }
  577. return false;
  578. }
  579. #endregion Url
  580. /// <summary>
  581. /// 转换成字节数组
  582. /// </summary>
  583. /// <param name="this"></param>
  584. /// <returns></returns>
  585. public static byte[] ToByteArray(this string @this)
  586. {
  587. return Encoding.UTF8.GetBytes(@this);
  588. }
  589. #region Crc32
  590. /// <summary>
  591. /// 获取字符串crc32签名
  592. /// </summary>
  593. /// <param name="s"></param>
  594. /// <returns></returns>
  595. public static string Crc32(this string s)
  596. {
  597. return string.Join(string.Empty, new Security.Crc32().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  598. }
  599. /// <summary>
  600. /// 获取字符串crc64签名
  601. /// </summary>
  602. /// <param name="s"></param>
  603. /// <returns></returns>
  604. public static string Crc64(this string s)
  605. {
  606. return string.Join(string.Empty, new Security.Crc64().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  607. }
  608. #endregion Crc32
  609. #region 权威校验中国专利申请号/专利号
  610. /// <summary>
  611. /// 中国专利申请号(授权以后就是专利号)由两种组成
  612. /// 2003年9月30号以前的9位(不带校验位是8号),校验位之前可能还会有一个点,例如:00262311, 002623110 或 00262311.0
  613. /// 2003年10月1号以后的13位(不带校验位是12号),校验位之前可能还会有一个点,例如:200410018477, 2004100184779 或200410018477.9
  614. /// http://www.sipo.gov.cn/docs/pub/old/wxfw/zlwxxxggfw/hlwzljsxt/hlwzljsxtsyzn/201507/P020150713610193194682.pdf
  615. /// 上面的文档中均不包括校验算法,但是下面的校验算法没有问题
  616. /// </summary>
  617. /// <param name="patnum">源字符串</param>
  618. /// <returns>是否匹配成功</returns>
  619. public static bool MatchCNPatentNumber(this string patnum)
  620. {
  621. Regex patnumWithCheckbitPattern = new Regex(@"^
  622. (?<!\d)
  623. (?<patentnum>
  624. (?<basenum>
  625. (?<year>(?<old>8[5-9]|9[0-9]|0[0-3])|(?<new>[2-9]\d{3}))
  626. (?<sn>
  627. (?<patenttype>[12389])
  628. (?(old)\d{5}|(?(new)\d{7}))
  629. )
  630. )
  631. (?:
  632. \.?
  633. (?<checkbit>[0-9X])
  634. )?
  635. )
  636. (?!\d)
  637. $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline);
  638. Match m = patnumWithCheckbitPattern.Match(patnum);
  639. if (!m.Success)
  640. {
  641. return false;
  642. }
  643. bool isPatnumTrue = true;
  644. patnum = patnum.ToUpper().Replace(".", "");
  645. if (patnum.Length == 9 || patnum.Length == 8)
  646. {
  647. byte[] factors8 = new byte[] { 2, 3, 4, 5, 6, 7, 8, 9 };
  648. int year = Convert.ToUInt16(patnum.Substring(0, 2));
  649. year += (year >= 85) ? (ushort)1900u : (ushort)2000u;
  650. if (year >= 1985 || year <= 2003)
  651. {
  652. int sum = 0;
  653. for (byte i = 0; i < 8; i++)
  654. {
  655. sum += factors8[i] * (patnum[i] - '0');
  656. }
  657. char checkbit = "0123456789X"[sum % 11];
  658. if (patnum.Length == 9)
  659. {
  660. if (checkbit != patnum[8])
  661. {
  662. isPatnumTrue = false;
  663. }
  664. }
  665. else
  666. {
  667. patnum += checkbit;
  668. }
  669. }
  670. else
  671. {
  672. isPatnumTrue = false;
  673. }
  674. }
  675. else if (patnum.Length == 13 || patnum.Length == 12)
  676. {
  677. byte[] factors12 = new byte[12] { 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5 };
  678. int year = Convert.ToUInt16(patnum.Substring(0, 4));
  679. if (year >= 2003 && year <= DateTime.Now.Year)
  680. {
  681. int sum = 0;
  682. for (byte i = 0; i < 12; i++)
  683. {
  684. sum += factors12[i] * (patnum[i] - '0');
  685. }
  686. char checkbit = "0123456789X"[sum % 11];
  687. if (patnum.Length == 13)
  688. {
  689. if (checkbit != patnum[12])
  690. {
  691. isPatnumTrue = false;
  692. }
  693. }
  694. else
  695. {
  696. patnum += checkbit;
  697. }
  698. }
  699. else
  700. {
  701. isPatnumTrue = false;
  702. }
  703. }
  704. else
  705. {
  706. isPatnumTrue = false;
  707. }
  708. return isPatnumTrue;
  709. }
  710. #endregion 权威校验中国专利申请号/专利号
  711. /// <summary>
  712. /// 取字符串前{length}个字
  713. /// </summary>
  714. /// <param name="s"></param>
  715. /// <param name="length"></param>
  716. /// <returns></returns>
  717. public static string Take(this string s, int length)
  718. {
  719. return s.Length > length ? s.Substring(0, length) : s;
  720. }
  721. /// <summary>
  722. /// 对比字符串的汉明距离
  723. /// </summary>
  724. /// <param name="this"></param>
  725. /// <param name="that"></param>
  726. /// <returns></returns>
  727. public static int HammingDistance(this string @this, string that) => new SimHash(@this).HammingDistance(new SimHash(that));
  728. /// <summary>
  729. /// 匹配字符串是否包含emoji字符
  730. /// </summary>
  731. /// <param name="s"></param>
  732. /// <returns></returns>
  733. public static bool MatchEmoji(this string s)
  734. {
  735. return Regex.IsMatch(s, @"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])");
  736. }
  737. }
  738. }