StringExtensions.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. /// 判断字符串不为空或""
  223. /// </summary>
  224. /// <param name="s"></param>
  225. /// <returns></returns>
  226. public static bool NotNullOrEmpty(this string s)
  227. {
  228. return !string.IsNullOrWhiteSpace(s) && !s.Equals("null", StringComparison.CurrentCultureIgnoreCase);
  229. }
  230. /// <summary>
  231. /// 转成非null
  232. /// </summary>
  233. /// <param name="s"></param>
  234. /// <returns></returns>
  235. public static string AsNotNull(this string s)
  236. {
  237. return string.IsNullOrEmpty(s) ? "" : s;
  238. }
  239. /// <summary>
  240. /// 转成非null
  241. /// </summary>
  242. /// <param name="s"></param>
  243. /// <param name="value">为空时的替换值</param>
  244. /// <returns></returns>
  245. public static string IfNullOrEmpty(this string s, string value)
  246. {
  247. return string.IsNullOrEmpty(s) ? value : s;
  248. }
  249. /// <summary>
  250. /// 转成非null
  251. /// </summary>
  252. /// <param name="s"></param>
  253. /// <param name="valueFactory">为空时的替换值函数</param>
  254. /// <returns></returns>
  255. public static string IfNullOrEmpty(this string s, Func<string> valueFactory)
  256. {
  257. return string.IsNullOrEmpty(s) ? valueFactory() : s;
  258. }
  259. /// <summary>
  260. /// 字符串掩码
  261. /// </summary>
  262. /// <param name="s">字符串</param>
  263. /// <param name="mask">掩码符</param>
  264. /// <returns></returns>
  265. public static string Mask(this string s, char mask = '*')
  266. {
  267. if (string.IsNullOrWhiteSpace(s?.Trim()))
  268. {
  269. return s;
  270. }
  271. s = s.Trim();
  272. string masks = mask.ToString().PadLeft(4, mask);
  273. return s.Length switch
  274. {
  275. >= 11 => Regex.Replace(s, "(.{3}).*(.{4})", $"$1{masks}$2"),
  276. 10 => Regex.Replace(s, "(.{3}).*(.{3})", $"$1{masks}$2"),
  277. 9 => Regex.Replace(s, "(.{2}).*(.{3})", $"$1{masks}$2"),
  278. 8 => Regex.Replace(s, "(.{2}).*(.{2})", $"$1{masks}$2"),
  279. 7 => Regex.Replace(s, "(.{1}).*(.{2})", $"$1{masks}$2"),
  280. 6 => Regex.Replace(s, "(.{1}).*(.{1})", $"$1{masks}$2"),
  281. _ => Regex.Replace(s, "(.{1}).*", $"$1{masks}")
  282. };
  283. }
  284. #region Email
  285. /// <summary>
  286. /// 匹配Email
  287. /// </summary>
  288. /// <param name="s">源字符串</param>
  289. /// <param name="valid">是否验证有效性</param>
  290. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  291. public static (bool isMatch, Match match) MatchEmail(this string s, bool valid = false)
  292. {
  293. if (string.IsNullOrEmpty(s) || s.Length < 7)
  294. {
  295. return (false, null);
  296. }
  297. var match = Regex.Match(s, @"[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+");
  298. var isMatch = match.Success;
  299. if (isMatch && valid)
  300. {
  301. var nslookup = new LookupClient();
  302. var task = nslookup.Query(s.Split('@')[1], QueryType.MX).Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  303. {
  304. if (t.IsCanceled || t.IsFaulted)
  305. {
  306. return new[]
  307. {
  308. IPAddress.Loopback
  309. };
  310. }
  311. return t.Result;
  312. }));
  313. isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  314. }
  315. return (isMatch, match);
  316. }
  317. /// <summary>
  318. /// 匹配Email
  319. /// </summary>
  320. /// <param name="s">源字符串</param>
  321. /// <param name="valid">是否验证有效性</param>
  322. /// <returns>匹配对象;是否匹配成功,若返回true,则会得到一个Match对象,否则为null</returns>
  323. public static async Task<(bool isMatch, Match match)> MatchEmailAsync(this string s, bool valid = false)
  324. {
  325. if (string.IsNullOrEmpty(s) || s.Length < 7)
  326. {
  327. return (false, null);
  328. }
  329. var match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  330. var isMatch = match.Success;
  331. if (isMatch && valid)
  332. {
  333. var nslookup = new LookupClient();
  334. using var cts = new CancellationTokenSource(100);
  335. var query = await nslookup.QueryAsync(s.Split('@')[1], QueryType.MX, cancellationToken: cts.Token);
  336. var result = await query.Answers.MxRecords().SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
  337. {
  338. if (t.IsCanceled || t.IsFaulted)
  339. {
  340. return new[] { IPAddress.Loopback };
  341. }
  342. return t.Result;
  343. }));
  344. isMatch = result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
  345. }
  346. return (isMatch, match);
  347. }
  348. /// <summary>
  349. /// 邮箱掩码
  350. /// </summary>
  351. /// <param name="s">邮箱</param>
  352. /// <param name="mask">掩码</param>
  353. /// <returns></returns>
  354. public static string MaskEmail(this string s, char mask = '*')
  355. {
  356. var index = s.LastIndexOf("@");
  357. var oldValue = s.Substring(0, index);
  358. return !MatchEmail(s).isMatch ? s : s.Replace(oldValue, Mask(oldValue, mask));
  359. }
  360. #endregion Email
  361. #region 匹配完整的URL
  362. /// <summary>
  363. /// 匹配完整格式的URL
  364. /// </summary>
  365. /// <param name="s">源字符串</param>
  366. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  367. /// <returns>匹配对象</returns>
  368. public static Uri MatchUrl(this string s, out bool isMatch)
  369. {
  370. try
  371. {
  372. var uri = new Uri(s);
  373. isMatch = Dns.GetHostAddresses(uri.Host).Any(ip => !ip.IsPrivateIP());
  374. return uri;
  375. }
  376. catch
  377. {
  378. isMatch = false;
  379. return null;
  380. }
  381. }
  382. /// <summary>
  383. /// 匹配完整格式的URL
  384. /// </summary>
  385. /// <param name="s">源字符串</param>
  386. /// <returns>是否匹配成功</returns>
  387. public static bool MatchUrl(this string s)
  388. {
  389. MatchUrl(s, out var isMatch);
  390. return isMatch;
  391. }
  392. #endregion 匹配完整的URL
  393. #region 权威校验身份证号码
  394. /// <summary>
  395. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  396. /// </summary>
  397. /// <param name="s">源字符串</param>
  398. /// <returns>是否匹配成功</returns>
  399. public static bool MatchIdentifyCard(this string s)
  400. {
  401. return s.Length switch
  402. {
  403. 18 => CheckChinaID18(s),
  404. 15 => CheckChinaID15(s),
  405. _ => false
  406. };
  407. }
  408. private static readonly string[] ChinaIDProvinceCodes = {
  409. "11", "12", "13", "14", "15",
  410. "21", "22", "23",
  411. "31", "32", "33", "34", "35", "36", "37",
  412. "41", "42", "43", "44", "45", "46",
  413. "50", "51", "52", "53", "54",
  414. "61", "62", "63", "64", "65",
  415. "71",
  416. "81",
  417. "82",
  418. "91"
  419. };
  420. private static bool CheckChinaID18(string ID)
  421. {
  422. ID = ID.ToUpper();
  423. Match m = Regex.Match(ID, @"\d{17}[\dX]", RegexOptions.IgnoreCase);
  424. if (!m.Success)
  425. {
  426. return false;
  427. }
  428. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  429. {
  430. return false;
  431. }
  432. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  433. if (!DateTime.TryParseExact(ID.Substring(6, 8), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  434. {
  435. return false;
  436. }
  437. if (!birthday.In(new DateTime(1800, 1, 1), DateTime.Today))
  438. {
  439. return false;
  440. }
  441. int[] factors = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
  442. int sum = 0;
  443. for (int i = 0; i < 17; i++)
  444. {
  445. sum += (ID[i] - '0') * factors[i];
  446. }
  447. int n = (12 - sum % 11) % 11;
  448. return n < 10 ? ID[17] - '0' == n : ID[17].Equals('X');
  449. }
  450. private static bool CheckChinaID15(string ID)
  451. {
  452. Match m = Regex.Match(ID, @"\d{15}", RegexOptions.IgnoreCase);
  453. if (!m.Success)
  454. {
  455. return false;
  456. }
  457. if (!ChinaIDProvinceCodes.Contains(ID.Substring(0, 2)))
  458. {
  459. return false;
  460. }
  461. CultureInfo zhCN = new CultureInfo("zh-CN", true);
  462. if (!DateTime.TryParseExact("19" + ID.Substring(6, 6), "yyyyMMdd", zhCN, DateTimeStyles.None, out DateTime birthday))
  463. {
  464. return false;
  465. }
  466. return birthday.In(new DateTime(1800, 1, 1), new DateTime(2000, 1, 1));
  467. }
  468. #endregion 权威校验身份证号码
  469. #region IP地址
  470. /// <summary>
  471. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  472. /// </summary>
  473. /// <param name="s">源字符串</param>
  474. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  475. /// <returns>匹配对象</returns>
  476. public static IPAddress MatchInetAddress(this string s, out bool isMatch)
  477. {
  478. isMatch = IPAddress.TryParse(s, out var ip);
  479. return ip;
  480. }
  481. /// <summary>
  482. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  483. /// </summary>
  484. /// <param name="s">源字符串</param>
  485. /// <returns>是否匹配成功</returns>
  486. public static bool MatchInetAddress(this string s)
  487. {
  488. MatchInetAddress(s, out var success);
  489. return success;
  490. }
  491. /// <summary>
  492. /// IP地址转换成数字
  493. /// </summary>
  494. /// <param name="addr">IP地址</param>
  495. /// <returns>数字,输入无效IP地址返回0</returns>
  496. public static uint IPToID(this string addr)
  497. {
  498. if (!IPAddress.TryParse(addr, out var ip))
  499. {
  500. return 0;
  501. }
  502. byte[] bInt = ip.GetAddressBytes();
  503. if (BitConverter.IsLittleEndian)
  504. {
  505. Array.Reverse(bInt);
  506. }
  507. return BitConverter.ToUInt32(bInt, 0);
  508. }
  509. /// <summary>
  510. /// IP地址转换成数字
  511. /// </summary>
  512. /// <param name="ip">IP地址</param>
  513. /// <returns>数字,输入无效IP地址返回0</returns>
  514. public static uint ToUInt32(this IPAddress ip)
  515. {
  516. byte[] bInt = ip.GetAddressBytes();
  517. if (BitConverter.IsLittleEndian)
  518. {
  519. Array.Reverse(bInt);
  520. }
  521. return BitConverter.ToUInt32(bInt, 0);
  522. }
  523. /// <summary>
  524. /// 判断IP是否是私有地址
  525. /// </summary>
  526. /// <param name="ip"></param>
  527. /// <returns></returns>
  528. public static bool IsPrivateIP(this string ip)
  529. {
  530. var address = MatchInetAddress(ip, out var b);
  531. return b && address.IsPrivateIP();
  532. }
  533. /// <summary>
  534. /// 判断IP地址在不在某个IP地址段
  535. /// </summary>
  536. /// <param name="input">需要判断的IP地址</param>
  537. /// <param name="begin">起始地址</param>
  538. /// <param name="ends">结束地址</param>
  539. /// <returns></returns>
  540. public static bool IpAddressInRange(this string input, string begin, string ends)
  541. {
  542. uint current = input.IPToID();
  543. return current >= begin.IPToID() && current <= ends.IPToID();
  544. }
  545. /// <summary>
  546. /// 判断IP地址在不在某个IP地址段
  547. /// </summary>
  548. /// <param name="input">需要判断的IP地址</param>
  549. /// <param name="begin">起始地址</param>
  550. /// <param name="ends">结束地址</param>
  551. /// <returns></returns>
  552. public static bool IpAddressInRange(this IPAddress input, IPAddress begin, IPAddress ends)
  553. {
  554. uint current = input.ToUInt32();
  555. return current >= begin.ToUInt32() && current <= ends.ToUInt32();
  556. }
  557. #endregion IP地址
  558. #region 校验手机号码的正确性
  559. /// <summary>
  560. /// 匹配手机号码
  561. /// </summary>
  562. /// <param name="s">源字符串</param>
  563. /// <returns>是否匹配成功</returns>
  564. public static bool MatchPhoneNumber(this string s)
  565. {
  566. return !string.IsNullOrEmpty(s) && s.Length == 11 && s[0] == '1' && (s[1] > '2' || s[1] <= '9') && long.TryParse(s, out _);
  567. }
  568. /// <summary>
  569. /// 匹配固话号码
  570. /// </summary>
  571. /// <param name="s">源字符串</param>
  572. /// <returns>是否匹配成功</returns>
  573. public static bool MatchLandline(this string s)
  574. {
  575. return Regex.IsMatch(s, @"^0\d{2,3}(?:-?\d{8}|-?\d{7})$");
  576. }
  577. #endregion 校验手机号码的正确性
  578. #region Url
  579. /// <summary>
  580. /// 判断url是否是外部地址
  581. /// </summary>
  582. /// <param name="url"></param>
  583. /// <returns></returns>
  584. public static bool IsExternalAddress(this string url)
  585. {
  586. var uri = new Uri(url);
  587. switch (uri.HostNameType)
  588. {
  589. case UriHostNameType.Dns:
  590. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  591. if (ipHostEntry.AddressList.Where(ipAddress => ipAddress.AddressFamily == AddressFamily.InterNetwork).Any(ipAddress => !ipAddress.IsPrivateIP()))
  592. {
  593. return true;
  594. }
  595. break;
  596. case UriHostNameType.IPv4:
  597. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  598. }
  599. return false;
  600. }
  601. #endregion Url
  602. /// <summary>
  603. /// 转换成字节数组
  604. /// </summary>
  605. /// <param name="this"></param>
  606. /// <returns></returns>
  607. public static byte[] ToByteArray(this string @this)
  608. {
  609. return Encoding.UTF8.GetBytes(@this);
  610. }
  611. #region Crc32
  612. /// <summary>
  613. /// 获取字符串crc32签名
  614. /// </summary>
  615. /// <param name="s"></param>
  616. /// <returns></returns>
  617. public static string Crc32(this string s)
  618. {
  619. return string.Join(string.Empty, new Security.Crc32().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  620. }
  621. /// <summary>
  622. /// 获取字符串crc64签名
  623. /// </summary>
  624. /// <param name="s"></param>
  625. /// <returns></returns>
  626. public static string Crc64(this string s)
  627. {
  628. return string.Join(string.Empty, new Security.Crc64().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(b => b.ToString("x2")));
  629. }
  630. #endregion Crc32
  631. #region 权威校验中国专利申请号/专利号
  632. /// <summary>
  633. /// 中国专利申请号(授权以后就是专利号)由两种组成
  634. /// 2003年9月30号以前的9位(不带校验位是8号),校验位之前可能还会有一个点,例如:00262311, 002623110 或 00262311.0
  635. /// 2003年10月1号以后的13位(不带校验位是12号),校验位之前可能还会有一个点,例如:200410018477, 2004100184779 或200410018477.9
  636. /// http://www.sipo.gov.cn/docs/pub/old/wxfw/zlwxxxggfw/hlwzljsxt/hlwzljsxtsyzn/201507/P020150713610193194682.pdf
  637. /// 上面的文档中均不包括校验算法,但是下面的校验算法没有问题
  638. /// </summary>
  639. /// <param name="patnum">源字符串</param>
  640. /// <returns>是否匹配成功</returns>
  641. public static bool MatchCNPatentNumber(this string patnum)
  642. {
  643. Regex patnumWithCheckbitPattern = new Regex(@"^
  644. (?<!\d)
  645. (?<patentnum>
  646. (?<basenum>
  647. (?<year>(?<old>8[5-9]|9[0-9]|0[0-3])|(?<new>[2-9]\d{3}))
  648. (?<sn>
  649. (?<patenttype>[12389])
  650. (?(old)\d{5}|(?(new)\d{7}))
  651. )
  652. )
  653. (?:
  654. \.?
  655. (?<checkbit>[0-9X])
  656. )?
  657. )
  658. (?!\d)
  659. $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline);
  660. Match m = patnumWithCheckbitPattern.Match(patnum);
  661. if (!m.Success)
  662. {
  663. return false;
  664. }
  665. bool isPatnumTrue = true;
  666. patnum = patnum.ToUpper().Replace(".", "");
  667. if (patnum.Length == 9 || patnum.Length == 8)
  668. {
  669. byte[] factors8 = new byte[] { 2, 3, 4, 5, 6, 7, 8, 9 };
  670. int year = Convert.ToUInt16(patnum.Substring(0, 2));
  671. year += (year >= 85) ? (ushort)1900u : (ushort)2000u;
  672. if (year >= 1985 || year <= 2003)
  673. {
  674. int sum = 0;
  675. for (byte i = 0; i < 8; i++)
  676. {
  677. sum += factors8[i] * (patnum[i] - '0');
  678. }
  679. char checkbit = "0123456789X"[sum % 11];
  680. if (patnum.Length == 9)
  681. {
  682. if (checkbit != patnum[8])
  683. {
  684. isPatnumTrue = false;
  685. }
  686. }
  687. }
  688. else
  689. {
  690. isPatnumTrue = false;
  691. }
  692. }
  693. else if (patnum.Length == 13 || patnum.Length == 12)
  694. {
  695. byte[] factors12 = { 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5 };
  696. int year = Convert.ToUInt16(patnum.Substring(0, 4));
  697. if (year >= 2003 && year <= DateTime.Now.Year)
  698. {
  699. int sum = 0;
  700. for (byte i = 0; i < 12; i++)
  701. {
  702. sum += factors12[i] * (patnum[i] - '0');
  703. }
  704. char checkbit = "0123456789X"[sum % 11];
  705. if (patnum.Length == 13)
  706. {
  707. if (checkbit != patnum[12])
  708. {
  709. isPatnumTrue = false;
  710. }
  711. }
  712. else
  713. {
  714. patnum += checkbit;
  715. }
  716. }
  717. else
  718. {
  719. isPatnumTrue = false;
  720. }
  721. }
  722. else
  723. {
  724. isPatnumTrue = false;
  725. }
  726. return isPatnumTrue;
  727. }
  728. #endregion 权威校验中国专利申请号/专利号
  729. /// <summary>
  730. /// 取字符串前{length}个字
  731. /// </summary>
  732. /// <param name="s"></param>
  733. /// <param name="length"></param>
  734. /// <returns></returns>
  735. public static string Take(this string s, int length)
  736. {
  737. return s.Length > length ? s.Substring(0, length) : s;
  738. }
  739. /// <summary>
  740. /// 对比字符串的汉明距离
  741. /// </summary>
  742. /// <param name="this"></param>
  743. /// <param name="that"></param>
  744. /// <returns></returns>
  745. public static int HammingDistance(this string @this, string that) => new SimHash(@this).HammingDistance(new SimHash(that));
  746. /// <summary>
  747. /// 匹配字符串是否包含emoji字符
  748. /// </summary>
  749. /// <param name="s"></param>
  750. /// <returns></returns>
  751. public static bool MatchEmoji(this string s)
  752. {
  753. return Regex.IsMatch(s, @"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])");
  754. }
  755. /// <summary>
  756. /// 获取字符串的字符数
  757. /// </summary>
  758. /// <param name="str"></param>
  759. /// <returns></returns>
  760. public static int CharacterCount(this string str)
  761. {
  762. var enumerator = StringInfo.GetTextElementEnumerator(str);
  763. int length = 0;
  764. while (enumerator.MoveNext())
  765. {
  766. length++;
  767. }
  768. return length;
  769. }
  770. /// <summary>
  771. /// 获取字符串的字节数
  772. /// </summary>
  773. /// <param name="str"></param>
  774. /// <returns></returns>
  775. public static int BytesCount(this string str)
  776. {
  777. return Encoding.UTF8.GetByteCount(str);
  778. }
  779. /// <summary>
  780. /// 转半角(DBC case)
  781. /// </summary>
  782. /// <param name="input">任意字符串</param>
  783. /// <returns>半角字符串</returns>
  784. ///<remarks>
  785. ///全角空格为12288,半角空格为32(此处不必转空格)
  786. ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
  787. ///</remarks>
  788. public static string ToDBC(this string input)
  789. {
  790. char[] c = input.ToCharArray();
  791. for (int i = 0; i < c.Length; i++)
  792. {
  793. if (c[i] == 12288)
  794. {
  795. c[i] = (char)32;
  796. continue;
  797. }
  798. if (c[i] > 65280 && c[i] < 65375)
  799. {
  800. c[i] = (char)(c[i] - 65248);
  801. }
  802. }
  803. return new string(c);
  804. }
  805. /// <summary>
  806. /// 转全角(SBC case)
  807. /// </summary>
  808. /// <param name="input">任意字符串</param>
  809. /// <returns>全角字符串</returns>
  810. ///<remarks>
  811. ///全角空格为12288,半角空格为32
  812. ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
  813. ///</remarks>
  814. public static string ToSBC(this string input)
  815. {
  816. //半角转全角:
  817. var c = input.ToCharArray();
  818. for (int i = 0; i < c.Length; i++)
  819. {
  820. if (c[i] == 32)
  821. {
  822. c[i] = (char)12288;
  823. continue;
  824. }
  825. if (c[i] < 127 && c[i] > 32)
  826. {
  827. c[i] = (char)(c[i] + 65248);
  828. }
  829. }
  830. return new string(c);
  831. }
  832. }
  833. }