StringExtensions.cs 25 KB

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