Extensions.cs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. using Masuit.Tools.Strings;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. namespace Masuit.Tools
  11. {
  12. /// <summary>
  13. /// 扩展方法
  14. /// </summary>
  15. public static class Extensions
  16. {
  17. #region SyncForEach
  18. /// <summary>
  19. /// 遍历数组
  20. /// </summary>
  21. /// <param name="objs"></param>
  22. /// <param name="action">回调方法</param>
  23. public static void ForEach(this object[] objs, Action<object> action)
  24. {
  25. foreach (var o in objs)
  26. {
  27. action(o);
  28. }
  29. }
  30. /// <summary>
  31. /// 遍历IEnumerable
  32. /// </summary>
  33. /// <param name="objs"></param>
  34. /// <param name="action">回调方法</param>
  35. public static void ForEach(this IEnumerable<dynamic> objs, Action<object> action)
  36. {
  37. foreach (var o in objs)
  38. {
  39. action(o);
  40. }
  41. }
  42. /// <summary>
  43. /// 遍历集合
  44. /// </summary>
  45. /// <param name="objs"></param>
  46. /// <param name="action">回调方法</param>
  47. public static void ForEach(this IList<dynamic> objs, Action<object> action)
  48. {
  49. foreach (var o in objs)
  50. {
  51. action(o);
  52. }
  53. }
  54. /// <summary>
  55. /// 遍历数组
  56. /// </summary>
  57. /// <param name="objs"></param>
  58. /// <param name="action">回调方法</param>
  59. /// <typeparam name="T"></typeparam>
  60. public static void ForEach<T>(this T[] objs, Action<T> action)
  61. {
  62. foreach (var o in objs)
  63. {
  64. action(o);
  65. }
  66. }
  67. /// <summary>
  68. /// 遍历IEnumerable
  69. /// </summary>
  70. /// <param name="objs"></param>
  71. /// <param name="action">回调方法</param>
  72. /// <typeparam name="T"></typeparam>
  73. public static void ForEach<T>(this IEnumerable<T> objs, Action<T> action)
  74. {
  75. foreach (var o in objs)
  76. {
  77. action(o);
  78. }
  79. }
  80. /// <summary>
  81. /// 遍历List
  82. /// </summary>
  83. /// <param name="objs"></param>
  84. /// <param name="action">回调方法</param>
  85. /// <typeparam name="T"></typeparam>
  86. public static void ForEach<T>(this IList<T> objs, Action<T> action)
  87. {
  88. foreach (var o in objs)
  89. {
  90. action(o);
  91. }
  92. }
  93. /// <summary>
  94. /// 遍历数组并返回一个新的List
  95. /// </summary>
  96. /// <param name="objs"></param>
  97. /// <param name="action">回调方法</param>
  98. /// <returns></returns>
  99. public static IEnumerable<T> ForEach<T>(this object[] objs, Func<object, T> action)
  100. {
  101. foreach (var o in objs)
  102. {
  103. yield return action(o);
  104. }
  105. }
  106. /// <summary>
  107. /// 遍历IEnumerable并返回一个新的List
  108. /// </summary>
  109. /// <param name="objs"></param>
  110. /// <param name="action">回调方法</param>
  111. /// <typeparam name="T"></typeparam>
  112. /// <returns></returns>
  113. public static IEnumerable<T> ForEach<T>(this IEnumerable<dynamic> objs, Func<object, T> action)
  114. {
  115. foreach (var o in objs)
  116. {
  117. yield return action(o);
  118. }
  119. }
  120. /// <summary>
  121. /// 遍历List并返回一个新的List
  122. /// </summary>
  123. /// <param name="objs"></param>
  124. /// <param name="action">回调方法</param>
  125. /// <typeparam name="T"></typeparam>
  126. /// <returns></returns>
  127. public static IEnumerable<T> ForEach<T>(this IList<dynamic> objs, Func<object, T> action)
  128. {
  129. foreach (var o in objs)
  130. {
  131. yield return action(o);
  132. }
  133. }
  134. /// <summary>
  135. /// 遍历数组并返回一个新的List
  136. /// </summary>
  137. /// <param name="objs"></param>
  138. /// <param name="action">回调方法</param>
  139. /// <typeparam name="T"></typeparam>
  140. /// <returns></returns>
  141. public static IEnumerable<T> ForEach<T>(this T[] objs, Func<T, T> action)
  142. {
  143. foreach (var o in objs)
  144. {
  145. yield return action(o);
  146. }
  147. }
  148. /// <summary>
  149. /// 遍历IEnumerable并返回一个新的List
  150. /// </summary>
  151. /// <param name="objs"></param>
  152. /// <param name="action">回调方法</param>
  153. /// <typeparam name="T"></typeparam>
  154. /// <returns></returns>
  155. public static IEnumerable<T> ForEach<T>(this IEnumerable<T> objs, Func<T, T> action)
  156. {
  157. foreach (var o in objs)
  158. {
  159. yield return action(o);
  160. }
  161. }
  162. /// <summary>
  163. /// 遍历List并返回一个新的List
  164. /// </summary>
  165. /// <param name="objs"></param>
  166. /// <param name="action">回调方法</param>
  167. /// <typeparam name="T"></typeparam>
  168. /// <returns></returns>
  169. public static IEnumerable<T> ForEach<T>(this IList<T> objs, Func<T, T> action)
  170. {
  171. foreach (var o in objs)
  172. {
  173. yield return action(o);
  174. }
  175. }
  176. #endregion
  177. #region AsyncForEach
  178. /// <summary>
  179. /// 遍历数组
  180. /// </summary>
  181. /// <param name="objs"></param>
  182. /// <param name="action">回调方法</param>
  183. public static async void ForEachAsync(this object[] objs, Action<object> action)
  184. {
  185. await Task.Run(() =>
  186. {
  187. Parallel.ForEach(objs, action);
  188. });
  189. }
  190. /// <summary>
  191. /// 遍历数组
  192. /// </summary>
  193. /// <param name="objs"></param>
  194. /// <param name="action">回调方法</param>
  195. /// <typeparam name="T"></typeparam>
  196. public static async void ForEachAsync<T>(this T[] objs, Action<T> action)
  197. {
  198. await Task.Run(() =>
  199. {
  200. Parallel.ForEach(objs, action);
  201. });
  202. }
  203. /// <summary>
  204. /// 遍历IEnumerable
  205. /// </summary>
  206. /// <param name="objs"></param>
  207. /// <param name="action">回调方法</param>
  208. /// <typeparam name="T"></typeparam>
  209. public static async void ForEachAsync<T>(this IEnumerable<T> objs, Action<T> action)
  210. {
  211. await Task.Run(() =>
  212. {
  213. Parallel.ForEach(objs, action);
  214. });
  215. }
  216. /// <summary>
  217. /// 遍历List
  218. /// </summary>
  219. /// <param name="objs"></param>
  220. /// <param name="action">回调方法</param>
  221. /// <typeparam name="T"></typeparam>
  222. public static async void ForEachAsync<T>(this IList<T> objs, Action<T> action)
  223. {
  224. await Task.Run(() =>
  225. {
  226. Parallel.ForEach(objs, action);
  227. });
  228. }
  229. #endregion
  230. #region Map
  231. /// <summary>
  232. /// 映射到目标类型(浅克隆)
  233. /// </summary>
  234. /// <param name="source">源</param>
  235. /// <typeparam name="TDestination">目标类型</typeparam>
  236. /// <returns>目标类型</returns>
  237. public static TDestination MapTo<TDestination>(this object source) where TDestination : new()
  238. {
  239. TDestination dest = new TDestination();
  240. dest.GetType().GetProperties().ForEach(p =>
  241. {
  242. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
  243. });
  244. return dest;
  245. }
  246. /// <summary>
  247. /// 映射到目标类型(浅克隆)
  248. /// </summary>
  249. /// <param name="source">源</param>
  250. /// <typeparam name="TDestination">目标类型</typeparam>
  251. /// <returns>目标类型</returns>
  252. public static async Task<TDestination> MapToAsync<TDestination>(this object source) where TDestination : new()
  253. {
  254. return await Task.Run(() =>
  255. {
  256. TDestination dest = new TDestination();
  257. dest.GetType().GetProperties().ForEach(p =>
  258. {
  259. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
  260. });
  261. return dest;
  262. });
  263. }
  264. /// <summary>
  265. /// 映射到目标类型(深克隆)
  266. /// </summary>
  267. /// <param name="source">源</param>
  268. /// <typeparam name="TDestination">目标类型</typeparam>
  269. /// <returns>目标类型</returns>
  270. public static TDestination Map<TDestination>(this object source) where TDestination : new() => JsonConvert.DeserializeObject<TDestination>(JsonConvert.SerializeObject(source));
  271. /// <summary>
  272. /// 映射到目标类型(深克隆)
  273. /// </summary>
  274. /// <param name="source">源</param>
  275. /// <typeparam name="TDestination">目标类型</typeparam>
  276. /// <returns>目标类型</returns>
  277. public static async Task<TDestination> MapAsync<TDestination>(this object source) where TDestination : new() => await Task.Run(() => JsonConvert.DeserializeObject<TDestination>(JsonConvert.SerializeObject(source)));
  278. /// <summary>
  279. /// 复制一个新的对象
  280. /// </summary>
  281. /// <typeparam name="T"></typeparam>
  282. /// <param name="source"></param>
  283. /// <returns></returns>
  284. public static T Copy<T>(this T source) where T : new()
  285. {
  286. T dest = new T();
  287. dest.GetType().GetProperties().ForEach(p =>
  288. {
  289. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
  290. });
  291. return dest;
  292. }
  293. /// <summary>
  294. /// 复制到一个现有对象
  295. /// </summary>
  296. /// <typeparam name="T"></typeparam>
  297. /// <param name="source">源对象</param>
  298. /// <param name="dest">目标对象</param>
  299. /// <returns></returns>
  300. public static T CopyTo<T>(this T source, T dest) where T : new()
  301. {
  302. dest.GetType().GetProperties().ForEach(p =>
  303. {
  304. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
  305. });
  306. return dest;
  307. }
  308. /// <summary>
  309. /// 复制一个新的对象
  310. /// </summary>
  311. /// <typeparam name="T"></typeparam>
  312. /// <param name="source"></param>
  313. /// <returns></returns>
  314. public static async Task<T> CopyAsync<T>(this T source) where T : new() => await Task.Run(() =>
  315. {
  316. T dest = new T();
  317. dest.GetType().GetProperties().ForEach(p =>
  318. {
  319. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(source));
  320. });
  321. return dest;
  322. });
  323. /// <summary>
  324. /// 映射到目标类型的集合
  325. /// </summary>
  326. /// <param name="source">源</param>
  327. /// <typeparam name="TDestination">目标类型</typeparam>
  328. /// <returns>目标类型集合</returns>
  329. public static IEnumerable<TDestination> ToList<TDestination>(this object[] source) where TDestination : new()
  330. {
  331. foreach (var o in source)
  332. {
  333. var dest = new TDestination();
  334. dest.GetType().GetProperties().ForEach(p =>
  335. {
  336. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
  337. });
  338. yield return dest;
  339. }
  340. }
  341. /// <summary>
  342. /// 映射到目标类型的集合
  343. /// </summary>
  344. /// <param name="source">源</param>
  345. /// <typeparam name="TDestination">目标类型</typeparam>
  346. /// <returns>目标类型集合</returns>
  347. public static async Task<IEnumerable<TDestination>> ToListAsync<TDestination>(this object[] source) where TDestination : new()
  348. {
  349. return await Task.Run(() =>
  350. {
  351. IList<TDestination> list = new List<TDestination>();
  352. foreach (var o in source)
  353. {
  354. var dest = new TDestination();
  355. dest.GetType().GetProperties().ForEach(p =>
  356. {
  357. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
  358. });
  359. list.Add(dest);
  360. }
  361. return list;
  362. });
  363. }
  364. /// <summary>
  365. /// 映射到目标类型的集合
  366. /// </summary>
  367. /// <param name="source">源</param>
  368. /// <typeparam name="TDestination">目标类型</typeparam>
  369. /// <returns>目标类型集合</returns>
  370. public static IEnumerable<TDestination> ToList<TDestination>(this IList<dynamic> source) where TDestination : new()
  371. {
  372. foreach (var o in source)
  373. {
  374. var dest = new TDestination();
  375. dest.GetType().GetProperties().ForEach(p =>
  376. {
  377. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
  378. });
  379. yield return dest;
  380. }
  381. }
  382. /// <summary>
  383. /// 映射到目标类型的集合
  384. /// </summary>
  385. /// <param name="source">源</param>
  386. /// <typeparam name="TDestination">目标类型</typeparam>
  387. /// <returns>目标类型集合</returns>
  388. public static async Task<IEnumerable<TDestination>> ToListAsync<TDestination>(this IList<dynamic> source) where TDestination : new()
  389. {
  390. return await Task.Run(() =>
  391. {
  392. IList<TDestination> list = new List<TDestination>();
  393. foreach (var o in source)
  394. {
  395. var dest = new TDestination();
  396. dest.GetType().GetProperties().ForEach(p =>
  397. {
  398. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
  399. });
  400. list.Add(dest);
  401. }
  402. return list;
  403. });
  404. }
  405. /// <summary>
  406. /// 映射到目标类型的集合
  407. /// </summary>
  408. /// <param name="source">源</param>
  409. /// <typeparam name="TDestination">目标类型</typeparam>
  410. /// <returns>目标类型集合</returns>
  411. public static IEnumerable<TDestination> ToList<TDestination>(this IEnumerable<dynamic> source) where TDestination : new()
  412. {
  413. foreach (var o in source)
  414. {
  415. var dest = new TDestination();
  416. dest.GetType().GetProperties().ForEach(p =>
  417. {
  418. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
  419. });
  420. yield return dest;
  421. }
  422. }
  423. /// <summary>
  424. /// 映射到目标类型的集合
  425. /// </summary>
  426. /// <param name="source">源</param>
  427. /// <typeparam name="TDestination">目标类型</typeparam>
  428. /// <returns>目标类型集合</returns>
  429. public static async Task<IEnumerable<TDestination>> ToListAsync<TDestination>(this IEnumerable<dynamic> source) where TDestination : new()
  430. {
  431. return await Task.Run(() =>
  432. {
  433. IList<TDestination> list = new List<TDestination>();
  434. foreach (var o in source)
  435. {
  436. var dest = new TDestination();
  437. dest.GetType().GetProperties().ForEach(p =>
  438. {
  439. p.SetValue(dest, source.GetType().GetProperty(p.Name)?.GetValue(o));
  440. });
  441. list.Add(dest);
  442. }
  443. return list;
  444. });
  445. }
  446. #endregion
  447. /// <summary>
  448. /// 转换成json字符串
  449. /// </summary>
  450. /// <param name="source"></param>
  451. /// <returns></returns>
  452. public static string ToJsonString(this object source) => JsonConvert.SerializeObject(source, new JsonSerializerSettings()
  453. {
  454. ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  455. });
  456. /// <summary>
  457. /// 转换成json字符串
  458. /// </summary>
  459. /// <param name="source"></param>
  460. /// <returns></returns>
  461. public static async Task<string> ToJsonStringAsync(this object source) => await Task.Run(() => JsonConvert.SerializeObject(source));
  462. #region UBB、HTML互转
  463. /// <summary>
  464. /// UBB代码处理函数
  465. /// </summary>
  466. /// <param name="ubbStr">输入UBB字符串</param>
  467. /// <returns>输出html字符串</returns>
  468. public static string UbbToHtml(this string ubbStr)
  469. {
  470. Regex r;
  471. Match m;
  472. #region 处理空格
  473. ubbStr = ubbStr.Replace(" ", "&nbsp;");
  474. #endregion
  475. #region 处理&符
  476. ubbStr = ubbStr.Replace("&", "&amp;");
  477. #endregion
  478. #region 处理单引号
  479. ubbStr = ubbStr.Replace("'", "’");
  480. #endregion
  481. #region 处理双引号
  482. ubbStr = ubbStr.Replace("\"", "&quot;");
  483. #endregion
  484. #region html标记符
  485. ubbStr = ubbStr.Replace("<", "&lt;");
  486. ubbStr = ubbStr.Replace(">", "&gt;");
  487. #endregion
  488. #region 处理换行
  489. //处理换行,在每个新行的前面添加两个全角空格
  490. r = new Regex(@"(\r\n((&nbsp;)| )+)(?<正文>\S+)", RegexOptions.IgnoreCase);
  491. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<BR>  " + m.Groups["正文"]);
  492. //处理换行,在每个新行的前面添加两个全角空格
  493. ubbStr = ubbStr.Replace("\r\n", "<BR>");
  494. #endregion
  495. #region 处[b][/b]标记
  496. r = new Regex(@"(\[b\])([ \S\t]*?)(\[\/b\])", RegexOptions.IgnoreCase);
  497. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<B>" + m.Groups[2] + "</B>");
  498. #endregion
  499. #region 处[i][/i]标记
  500. r = new Regex(@"(\[i\])([ \S\t]*?)(\[\/i\])", RegexOptions.IgnoreCase);
  501. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<I>" + m.Groups[2] + "</I>");
  502. #endregion
  503. #region 处[u][/u]标记
  504. r = new Regex(@"(\[U\])([ \S\t]*?)(\[\/U\])", RegexOptions.IgnoreCase);
  505. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<U>" + m.Groups[2] + "</U>");
  506. #endregion
  507. #region 处[p][/p]标记
  508. //处[p][/p]标记
  509. r = new Regex(@"((\r\n)*\[p\])(.*?)((\r\n)*\[\/p\])", RegexOptions.IgnoreCase | RegexOptions.Singleline);
  510. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<P class=\"pstyle\">" + m.Groups[3] + "</P>");
  511. #endregion
  512. #region 处[sup][/sup]标记
  513. //处[sup][/sup]标记
  514. r = new Regex(@"(\[sup\])([ \S\t]*?)(\[\/sup\])", RegexOptions.IgnoreCase);
  515. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<SUP>" + m.Groups[2] + "</SUP>");
  516. #endregion
  517. #region 处[sub][/sub]标记
  518. //处[sub][/sub]标记
  519. r = new Regex(@"(\[sub\])([ \S\t]*?)(\[\/sub\])", RegexOptions.IgnoreCase);
  520. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<SUB>" + m.Groups[2] + "</SUB>");
  521. #endregion
  522. #region 处标记
  523. //处标记
  524. r = new Regex(@"(\[url\])([ \S\t]*?)(\[\/url\])", RegexOptions.IgnoreCase);
  525. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  526. {
  527. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<A href=\"" + m.Groups[2] + "\" target=\"_blank\">" + m.Groups[2] + "</A>");
  528. }
  529. #endregion
  530. #region 处[url=xxx][/url]标记
  531. //处[url=xxx][/url]标记
  532. r = new Regex(@"(\[url=([ \S\t]+)\])([ \S\t]*?)(\[\/url\])", RegexOptions.IgnoreCase);
  533. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  534. {
  535. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<A href=\"" + m.Groups[2] + "\" target=\"_blank\">" + m.Groups[3] + "</A>");
  536. }
  537. #endregion
  538. #region 处[email][/email]标记
  539. //处[email][/email]标记
  540. r = new Regex(@"(\[email\])([ \S\t]*?)(\[\/email\])", RegexOptions.IgnoreCase);
  541. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  542. {
  543. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<A href=\"mailto:" + m.Groups[2] + "\" target=\"_blank\">" + m.Groups[2] + "</A>");
  544. }
  545. #endregion
  546. #region 处[email=xxx][/email]标记
  547. //处[email=xxx][/email]标记
  548. r = new Regex(@"(\[email=([ \S\t]+)\])([ \S\t]*?)(\[\/email\])", RegexOptions.IgnoreCase);
  549. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  550. {
  551. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<A href=\"mailto:" + m.Groups[2] + "\" target=\"_blank\">" + m.Groups[3] + "</A>");
  552. }
  553. #endregion
  554. #region 处[size=x][/size]标记
  555. //处[size=x][/size]标记
  556. r = new Regex(@"(\[size=([1-7])\])([ \S\t]*?)(\[\/size\])", RegexOptions.IgnoreCase);
  557. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  558. {
  559. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<FONT SIZE=" + m.Groups[2] + ">" + m.Groups[3] + "</FONT>");
  560. }
  561. #endregion
  562. #region 处[color=x][/color]标记
  563. //处[color=x][/color]标记
  564. r = new Regex(@"(\[color=([\S]+)\])([ \S\t]*?)(\[\/color\])", RegexOptions.IgnoreCase);
  565. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  566. {
  567. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<FONT COLOR=" + m.Groups[2] + ">" + m.Groups[3] + "</FONT>");
  568. }
  569. #endregion
  570. #region 处[font=x][/font]标记
  571. //处[font=x][/font]标记
  572. r = new Regex(@"(\[font=([\S]+)\])([ \S\t]*?)(\[\/font\])", RegexOptions.IgnoreCase);
  573. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  574. {
  575. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<FONT FACE=" + m.Groups[2] + ">" + m.Groups[3] + "</FONT>");
  576. }
  577. #endregion
  578. #region 处理图片链接
  579. //处理图片链接
  580. r = new Regex("\\[picture\\](\\d+?)\\[\\/picture\\]", RegexOptions.IgnoreCase);
  581. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  582. {
  583. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<A href=\"ShowImage.aspx?Type=ALL&Action=forumImage&ImageID=" + m.Groups[1] + "\" target=\"_blank\"><IMG border=0 Title=\"点击打开新窗口查看\" src=\"ShowImage.aspx?Action=forumImage&ImageID=" + m.Groups[1] + "\"></A>");
  584. }
  585. #endregion
  586. #region 处理[align=x][/align]
  587. //处理[align=x][/align]
  588. r = new Regex(@"(\[align=([\S]+)\])([ \S\t]*?)(\[\/align\])", RegexOptions.IgnoreCase);
  589. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  590. {
  591. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<P align=" + m.Groups[2] + ">" + m.Groups[3] + "</P>");
  592. }
  593. #endregion
  594. #region 处[H=x][/H]标记
  595. //处[H=x][/H]标记
  596. r = new Regex(@"(\[H=([1-6])\])([ \S\t]*?)(\[\/H\])", RegexOptions.IgnoreCase);
  597. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  598. {
  599. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<H" + m.Groups[2] + ">" + m.Groups[3] + "</H" + m.Groups[2] + ">");
  600. }
  601. #endregion
  602. #region 处理[list=x][*][/list]
  603. //处理[list=x][*][/list]
  604. r = new Regex(@"(\[list(=(A|a|I|i| ))?\]([ \S\t]*)\r\n)((\[\*\]([ \S\t]*\r\n))*?)(\[\/list\])", RegexOptions.IgnoreCase);
  605. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  606. {
  607. string strLi = m.Groups[5].ToString();
  608. Regex rLi = new Regex(@"\[\*\]([ \S\t]*\r\n?)", RegexOptions.IgnoreCase);
  609. Match mLi;
  610. for (mLi = rLi.Match(strLi); mLi.Success; mLi = mLi.NextMatch()) strLi = strLi.Replace(mLi.Groups[0].ToString(), "<LI>" + mLi.Groups[1]);
  611. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<UL TYPE=\"" + m.Groups[3] + "\"><B>" + m.Groups[4] + "</B>" + strLi + "</UL>");
  612. }
  613. #endregion
  614. #region 处[SHADOW=x][/SHADOW]标记
  615. //处[SHADOW=x][/SHADOW]标记
  616. r = new Regex(@"(\[SHADOW=)(\d*?),(#*\w*?),(\d*?)\]([\S\t]*?)(\[\/SHADOW\])", RegexOptions.IgnoreCase);
  617. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  618. {
  619. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<TABLE WIDTH=" + m.Groups[2] + "STYLE=FILTER:SHADOW(COLOR=" + m.Groups[3] + ",STRENGTH=" + m.Groups[4] + ")>" + m.Groups[5] + "</TABLE>");
  620. }
  621. #endregion
  622. #region 处[glow=x][/glow]标记
  623. //处[glow=x][/glow]标记
  624. r = new Regex(@"(\[glow=)(\d*?),(#*\w*?),(\d*?)\]([\S\t]*?)(\[\/glow\])", RegexOptions.IgnoreCase);
  625. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  626. {
  627. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<TABLE WIDTH=" + m.Groups[2] + " STYLE=FILTER:GLOW(COLOR=" + m.Groups[3] + ", STRENGTH=" + m.Groups[4] + ")>" + m.Groups[5] + "</TABLE>");
  628. }
  629. #endregion
  630. #region 处[center][/center]标记
  631. r = new Regex(@"(\[center\])([ \S\t]*?)(\[\/center\])", RegexOptions.IgnoreCase);
  632. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<CENTER>" + m.Groups[2] + "</CENTER>");
  633. #endregion
  634. #region 处[ IMG][ /IMG]标记
  635. r = new Regex(@"(\[IMG\])(http|https|ftp):\/\/([ \S\t]*?)(\[\/IMG\])", RegexOptions.IgnoreCase);
  636. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<br><a onfocus=this.blur() href=" + m.Groups[2] + "://" + m.Groups[3] + " target=_blank><IMG SRC=" + m.Groups[2] + "://" + m.Groups[3] + " border=0 alt=按此在新窗口浏览图片 onload=javascript:if(screen.width-333<this.width)this.width=screen.width-333></a>");
  637. #endregion
  638. #region 处[em]标记
  639. r = new Regex(@"(\[em([\S\t]*?)\])", RegexOptions.IgnoreCase);
  640. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<img src=pic/em" + m.Groups[2] + ".gif border=0 align=middle>");
  641. #endregion
  642. #region 处[flash=x][/flash]标记
  643. //处[mp=x][/mp]标记
  644. r = new Regex(@"(\[flash=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/flash\])", RegexOptions.IgnoreCase);
  645. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  646. {
  647. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<a href=" + m.Groups[4] + " TARGET=_blank><IMG SRC=pic/swf.gif border=0 alt=点击开新窗口欣赏该FLASH动画!> [全屏欣赏]</a><br><br><OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 width=" + m.Groups[2] + " height=" + m.Groups[3] + "><PARAM NAME=movie VALUE=" + m.Groups[4] + "><PARAM NAME=quality VALUE=high><param name=menu value=false><embed src=" + m.Groups[4] + " quality=high menu=false pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash width=" + m.Groups[2] + " height=" + m.Groups[3] + ">" + m.Groups[4] + "</embed></OBJECT>");
  648. }
  649. #endregion
  650. #region 处[dir=x][/dir]标记
  651. //处[dir=x][/dir]标记
  652. r = new Regex(@"(\[dir=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/dir\])", RegexOptions.IgnoreCase);
  653. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  654. {
  655. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<object classid=clsid:166B1BCA-3F9C-11CF-8075-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0 width=" + m.Groups[2] + " height=" + m.Groups[3] + "><param name=src value=" + m.Groups[4] + "><embed src=" + m.Groups[4] + " pluginspage=http://www.macromedia.com/shockwave/download/ width=" + m.Groups[2] + " height=" + m.Groups[3] + "></embed></object>");
  656. }
  657. #endregion
  658. #region 处[rm=x][/rm]标记
  659. //处[rm=x][/rm]标记
  660. r = new Regex(@"(\[rm=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/rm\])", RegexOptions.IgnoreCase);
  661. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  662. {
  663. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<OBJECT classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA class=OBJECT id=RAOCX width=" + m.Groups[2] + " height=" + m.Groups[3] + "><PARAM NAME=SRC VALUE=" + m.Groups[4] + "><PARAM NAME=CONSOLE VALUE=Clip1><PARAM NAME=CONTROLS VALUE=imagewindow><PARAM NAME=AUTOSTART VALUE=true></OBJECT><br><OBJECT classid=CLSID:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA height=32 id=video2 width=" + m.Groups[2] + "><PARAM NAME=SRC VALUE=" + m.Groups[4] + "><PARAM NAME=AUTOSTART VALUE=-1><PARAM NAME=CONTROLS VALUE=controlpanel><PARAM NAME=CONSOLE VALUE=Clip1></OBJECT>");
  664. }
  665. #endregion
  666. #region 处[mp=x][/mp]标记
  667. //处[mp=x][/mp]标记
  668. r = new Regex(@"(\[mp=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/mp\])", RegexOptions.IgnoreCase);
  669. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  670. {
  671. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<object align=middle classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 class=OBJECT id=MediaPlayer width=" + m.Groups[2] + " height=" + m.Groups[3] + " ><param name=ShowStatusBar value=-1><param name=Filename value=" + m.Groups[4] + "><embed type=application/x-oleobject codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 flename=mp src=" + m.Groups[4] + " width=" + m.Groups[2] + " height=" + m.Groups[3] + "></embed></object>");
  672. }
  673. #endregion
  674. #region 处[qt=x][/qt]标记
  675. //处[qt=x][/qt]标记
  676. r = new Regex(@"(\[qt=)(\d*?),(\d*?)\]([\S\t]*?)(\[\/qt\])", RegexOptions.IgnoreCase);
  677. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  678. {
  679. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<embed src=" + m.Groups[4] + " width=" + m.Groups[2] + " height=" + m.Groups[3] + " autoplay=true loop=false controller=true playeveryframe=false cache=false scale=TOFIT bgcolor=#000000 kioskmode=false targetcache=false pluginspage=http://www.apple.com/quicktime/>");
  680. }
  681. #endregion
  682. #region 处[QUOTE][/QUOTE]标记
  683. r = new Regex(@"(\[QUOTE\])([ \S\t]*?)(\[\/QUOTE\])", RegexOptions.IgnoreCase);
  684. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<div style='border:#CCCCCC 1px dashed; width:94%; color:#999999; padding:3px; background:#F8F8F8'>" + m.Groups[2] + "</div><br /> ");
  685. #endregion
  686. #region 处[move][/move]标记
  687. r = new Regex(@"(\[move\])([ \S\t]*?)(\[\/move\])", RegexOptions.IgnoreCase);
  688. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<MARQUEE scrollamount=3>" + m.Groups[2] + "</MARQUEE>");
  689. #endregion
  690. #region 处[FLY][/FLY]标记
  691. r = new Regex(@"(\[FLY\])([ \S\t]*?)(\[\/FLY\])", RegexOptions.IgnoreCase);
  692. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch()) ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<MARQUEE width=80% behavior=alternate scrollamount=3>" + m.Groups[2] + "</MARQUEE>");
  693. #endregion
  694. #region 处[image][/image]标记
  695. //处[image][/image]标记
  696. r = new Regex(@"(\[image\])([ \S\t]*?)(\[\/image\])", RegexOptions.IgnoreCase);
  697. for (m = r.Match(ubbStr); m.Success; m = m.NextMatch())
  698. {
  699. ubbStr = ubbStr.Replace(m.Groups[0].ToString(), "<img src=\"" + m.Groups[2] + "\" border=0 align=middle><br>");
  700. }
  701. #endregion
  702. return ubbStr;
  703. }
  704. /// <summary>
  705. /// UBB代码处理函数
  706. /// </summary>
  707. /// <param name="ubbStr">输入UBB字符串</param>
  708. /// <returns>输出html字符串</returns>
  709. public static async Task<string> UbbToHtmlAsync(this string ubbStr) => await Task.Run(() => UbbToHtml(ubbStr));
  710. /// <summary>
  711. /// UBB转HTML方式2
  712. /// </summary>
  713. /// <param name="ubbStr">UBB 代码</param>
  714. /// <returns>HTML代码</returns>
  715. public static string UbbToHtml2(this string ubbStr)
  716. {
  717. ubbStr = ubbStr.Replace("&", "&amp;");
  718. ubbStr = ubbStr.Replace("<", "&lt;");
  719. ubbStr = ubbStr.Replace(">", "&gt;");
  720. ubbStr = ubbStr.Replace(" ", "&nbsp;"); //空格
  721. ubbStr = ubbStr.Replace("\n", "<br>"); //回车
  722. Regex my = new Regex(@"(\[IMG\])(.[^\[]*)(\[\/IMG\])", RegexOptions.IgnoreCase);
  723. ubbStr = my.Replace(ubbStr, @"<a href=""$2"" target=_blank><IMG SRC=""$2"" border=0 alt=按此在新窗口浏览图片 onload=""javascript:if(this.width>screen.width-333)this.width=screen.width-333""></a>");
  724. my = new Regex(@"\[DIR=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/DIR]", RegexOptions.IgnoreCase);
  725. ubbStr = my.Replace(ubbStr, @"<object classid=clsid:166B1BCA-3F9C-11CF-8075-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0 width=$1 height=$2><param name=src value=$3><embed src=$3 pluginspage=http://www.macromedia.com/shockwave/download/ width=$1 height=$2></embed></object>");
  726. my = new Regex(@"\[QT=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/QT]", RegexOptions.IgnoreCase);
  727. ubbStr = my.Replace(ubbStr, @"<embed src=$3 width=$1 height=$2 autoplay=true loop=false controller=true playeveryframe=false cache=false scale=TOFIT bgcolor=#000000 kioskmode=false targetcache=false pluginspage=http://www.apple.com/quicktime/>");
  728. my = new Regex(@"\[MP=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/MP]", RegexOptions.IgnoreCase);
  729. ubbStr = my.Replace(ubbStr, @"<object align=middle classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 class=OBJECT id=MediaPlayer width=$1 height=$2 ><param name=ShowStatusBar value=-1><param name=Filename value=$3><embed type=application/x-oleobject codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 flename=mp src=$3 width=$1 height=$2></embed></object>");
  730. my = new Regex(@"\[RM=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/RM]", RegexOptions.IgnoreCase);
  731. ubbStr = my.Replace(ubbStr, @"<OBJECT classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA class=OBJECT id=RAOCX width=$1 height=$2><PARAM NAME=SRC VALUE=$3><PARAM NAME=CONSOLE VALUE=Clip1><PARAM NAME=CONTROLS VALUE=imagewindow><PARAM NAME=AUTOSTART VALUE=true></OBJECT><br><OBJECT classid=CLSID:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA height=32 id=video2 width=$1><PARAM NAME=SRC VALUE=$3><PARAM NAME=AUTOSTART VALUE=-1><PARAM NAME=CONTROLS VALUE=controlpanel><PARAM NAME=CONSOLE VALUE=Clip1></OBJECT>");
  732. my = new Regex(@"(\[FLASH\])(.[^\[]*)(\[\/FLASH\])", RegexOptions.IgnoreCase);
  733. ubbStr = my.Replace(ubbStr, @"<OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 width=500 height=400><PARAM NAME=movie VALUE=""$2""><PARAM NAME=quality VALUE=high><embed src=""$2"" quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width=500 height=400>$2</embed></OBJECT>");
  734. my = new Regex(@"(\[ZIP\])(.[^\[]*)(\[\/ZIP\])", RegexOptions.IgnoreCase);
  735. ubbStr = my.Replace(ubbStr, @"<br><IMG SRC=pic/zip.gif border=0> <a href=""$2"">点击下载该文件</a>");
  736. my = new Regex(@"(\[RAR\])(.[^\[]*)(\[\/RAR\])", RegexOptions.IgnoreCase);
  737. ubbStr = my.Replace(ubbStr, @"<br><IMG SRC=pic/rar.gif border=0> <a href=""$2"">点击下载该文件</a>");
  738. my = new Regex(@"(\[UPLOAD=(.[^\[]*)\])(.[^\[]*)(\[\/UPLOAD\])", RegexOptions.IgnoreCase);
  739. ubbStr = my.Replace(ubbStr, @"<br><IMG SRC=""pic/$2.gif"" border=0>此主题相关图片如下:<br><A HREF=""$3"" TARGET=_blank><IMG SRC=""$3"" border=0 alt=按此在新窗口浏览图片 onload=""javascript:if(this.width>screen.width-333)this.width=screen.width-333""></A>");
  740. my = new Regex(@"(\[URL\])(http:\/\/.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
  741. ubbStr = my.Replace(ubbStr, @"<A HREF=""$2"" TARGET=_blank>$2</A>");
  742. my = new Regex(@"(\[URL\])(.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
  743. ubbStr = my.Replace(ubbStr, @"<A HREF=""http://$2"" TARGET=_blank>$2</A>");
  744. my = new Regex(@"(\[URL=(http:\/\/.[^\[]*)\])(.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
  745. ubbStr = my.Replace(ubbStr, @"<A HREF=""$2"" TARGET=_blank>$3</A>");
  746. my = new Regex(@"(\[URL=(.[^\[]*)\])(.[^\[]*)(\[\/URL\])", RegexOptions.IgnoreCase);
  747. ubbStr = my.Replace(ubbStr, @"<A HREF=""http://$2"" TARGET=_blank>$3</A>");
  748. my = new Regex(@"(\[EMAIL\])(\S+\@.[^\[]*)(\[\/EMAIL\])", RegexOptions.IgnoreCase);
  749. ubbStr = my.Replace(ubbStr, @"<A HREF=""mailto:$2"">$2</A>");
  750. my = new Regex(@"(\[EMAIL=(\S+\@.[^\[]*)\])(.[^\[]*)(\[\/EMAIL\])", RegexOptions.IgnoreCase);
  751. ubbStr = my.Replace(ubbStr, @"<A HREF=""mailto:$2"" TARGET=_blank>$3</A>");
  752. my = new Regex(@"^(HTTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  753. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  754. my = new Regex(@"(HTTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
  755. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  756. my = new Regex(@"[^>=""](HTTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  757. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  758. my = new Regex(@"^(FTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  759. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  760. my = new Regex(@"(FTP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
  761. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  762. my = new Regex(@"[^>=""](FTP://[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  763. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  764. my = new Regex(@"^(RTSP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  765. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  766. my = new Regex(@"(RTSP://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
  767. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  768. my = new Regex(@"[^>=""](RTSP://[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  769. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  770. my = new Regex(@"^(MMS://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  771. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  772. my = new Regex(@"(MMS://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)$", RegexOptions.IgnoreCase);
  773. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  774. my = new Regex(@"[^>=""](MMS://[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)", RegexOptions.IgnoreCase);
  775. ubbStr = my.Replace(ubbStr, @"<a target=_blank href=$1>$1</a>");
  776. my = new Regex(@"(\[HTML\])(.[^\[]*)(\[\/HTML\])", RegexOptions.IgnoreCase);
  777. ubbStr = my.Replace(ubbStr, @"<table width='100%' border='0' cellspacing='0' cellpadding='6' bgcolor=''><td><b>以下内容为程序代码:</b><br>$2</td></table>");
  778. my = new Regex(@"(\[CODE\])(.[^\[]*)(\[\/CODE\])", RegexOptions.IgnoreCase);
  779. ubbStr = my.Replace(ubbStr, @"<table width='100%' border='0' cellspacing='0' cellpadding='6' bgcolor=''><td><b>以下内容为程序代码:</b><br>$2</td></table>");
  780. my = new Regex(@"(\[COLOR=(.[^\[]*)\])(.[^\[]*)(\[\/COLOR\])", RegexOptions.IgnoreCase);
  781. ubbStr = my.Replace(ubbStr, @"<font COLOR=$2>$3</font>");
  782. my = new Regex(@"(\[FACE=(.[^\[]*)\])(.[^\[]*)(\[\/FACE\])", RegexOptions.IgnoreCase);
  783. ubbStr = my.Replace(ubbStr, @"<font FACE=$2>$3</font>");
  784. my = new Regex(@"(\[ALIGN=(.[^\[]*)\])(.*)(\[\/ALIGN\])", RegexOptions.IgnoreCase);
  785. ubbStr = my.Replace(ubbStr, @"<div ALIGN=$2>$3</div>");
  786. my = new Regex(@"(\[QUOTE\])(.*)(\[\/QUOTE\])", RegexOptions.IgnoreCase);
  787. ubbStr = my.Replace(ubbStr, @"<table cellpadding=0 cellspacing=0 border=0 WIDTH=94% bgcolor=#000000 align=center><tr><td><table width=100% cellpadding=5 cellspacing=1 border=0><TR><TD BGCOLOR=''>$2</table></table><br>");
  788. my = new Regex(@"(\[MOVE\])(.*)(\[\/MOVE\])", RegexOptions.IgnoreCase);
  789. ubbStr = my.Replace(ubbStr, @"<MARQUEE scrollamount=3>$2</marquee>");
  790. my = new Regex(@"\[GLOW=*([0-9]*),*(#*[a-z0-9]*),*([0-9]*)\](.[^\[]*)\[\/GLOW]", RegexOptions.IgnoreCase);
  791. ubbStr = my.Replace(ubbStr, @"<table width=$1 style=""filter:glow(color=$2, strength=$3)"">$4</table>");
  792. my = new Regex(@"\[SHADOW=*([0-9]*),*(#*[a-z0-9]*),*([0-9]*)\](.[^\[]*)\[\/SHADOW]", RegexOptions.IgnoreCase);
  793. ubbStr = my.Replace(ubbStr, @"<table width=$1 style=""filter:shadow(color=$2, strength=$3)"">$4</table>");
  794. my = new Regex(@"(\[I\])(.[^\[]*)(\[\/I\])", RegexOptions.IgnoreCase);
  795. ubbStr = my.Replace(ubbStr, @"<i>$2</i>");
  796. my = new Regex(@"(\[B\])(.[^\[]*)(\[\/U\])", RegexOptions.IgnoreCase);
  797. ubbStr = my.Replace(ubbStr, @"<u>$2</u>");
  798. my = new Regex(@"(\[B\])(.[^\[]*)(\[\/B\])", RegexOptions.IgnoreCase);
  799. ubbStr = my.Replace(ubbStr, @"<b>$2</b>");
  800. my = new Regex(@"(\[FLY\])(.[^\[]*)(\[\/FLY\])", RegexOptions.IgnoreCase);
  801. ubbStr = my.Replace(ubbStr, @"<marquee onmouseover='this.stop();' onmouseout='this.start();'>$2</marquee>");
  802. my = new Regex(@"(\[SIZE=1\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
  803. ubbStr = my.Replace(ubbStr, @"<font size=1>$2</font>");
  804. my = new Regex(@"(\[SIZE=2\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
  805. ubbStr = my.Replace(ubbStr, @"<font size=2>$2</font>");
  806. my = new Regex(@"(\[SIZE=3\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
  807. ubbStr = my.Replace(ubbStr, @"<font size=3>$2</font>");
  808. my = new Regex(@"(\[SIZE=4\])(.[^\[]*)(\[\/SIZE\])", RegexOptions.IgnoreCase);
  809. ubbStr = my.Replace(ubbStr, @"<font size=4>$2</font>");
  810. my = new Regex(@"(\[CENTER\])(.[^\[]*)(\[\/CENTER\])", RegexOptions.IgnoreCase);
  811. ubbStr = my.Replace(ubbStr, @"<center>$2</center>");
  812. return ubbStr;
  813. }
  814. /// <summary>
  815. /// UBB转HTML方式2
  816. /// </summary>
  817. /// <param name="ubbStr">UBB 代码</param>
  818. /// <returns>HTML代码</returns>
  819. public static async Task<string> UbbToHtml2Async(this string ubbStr) => await Task.Run(() => UbbToHtml2(ubbStr));
  820. /// <summary>
  821. /// Html转UBB
  822. /// </summary>
  823. /// <param name="chr">HTML代码</param>
  824. /// <returns>UBB代码</returns>
  825. public static string HtmltoUBB(this string chr)
  826. {
  827. if (chr == null) return "";
  828. chr = chr.Replace("&lt", "<");
  829. chr = chr.Replace("&gt", ">");
  830. chr = chr.Replace("<br/>", " ");
  831. chr = Regex.Replace(chr, @"<a href=$1 target=_blank>$2</a>", @"[url=(?<x>[^]]*)](?<y>[^]]*)[/url]", RegexOptions.IgnoreCase);
  832. chr = Regex.Replace(chr, @"<a href=$1 target=_blank>$1</a>", @"[url](?<x>[^]]*)[/url]", RegexOptions.IgnoreCase);
  833. chr = Regex.Replace(chr, @"<a href=$1>$2</a>", @"[email=(?<x>[^]]*)](?<y>[^]]*)[/email]", RegexOptions.IgnoreCase);
  834. chr = Regex.Replace(chr, @"<a href=$1>$1</a>", @"[email](?<x>[^]]*)[/email]", RegexOptions.IgnoreCase);
  835. chr = Regex.Replace(chr, @"<OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 width=500 height=400><PARAM NAME=movie VALUE=""$1""><PARAM NAME=quality VALUE=high><embed src=""$1"" quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width=500 height=400>$1</embed></OBJECT>", @"[flash](?<x>[^]]*)[/flash]", RegexOptions.IgnoreCase);
  836. chr = Regex.Replace(chr, @"<IMG SRC=""$1"" border=0>", @"[img](?<x>[^]]*)[/img]", RegexOptions.IgnoreCase);
  837. chr = Regex.Replace(chr, @"<font color=$1>$2</font>", @"[color=(?<x>[^]]*)](?<y>[^]]*)[/color]", RegexOptions.IgnoreCase);
  838. chr = Regex.Replace(chr, @"<font face=$1>$2</font>", @"[face=(?<x>[^]]*)](?<y>[^]]*)[/face]", RegexOptions.IgnoreCase);
  839. chr = Regex.Replace(chr, @"<font size=1>$1</font>", @"[size=1](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
  840. chr = Regex.Replace(chr, @"<font size=2>$1</font>", @"[size=2](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
  841. chr = Regex.Replace(chr, @"<font size=3>$1</font>", @"[size=3](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
  842. chr = Regex.Replace(chr, @"<font size=4>$1</font>", @"[size=4](?<x>[^]]*)[/size]", RegexOptions.IgnoreCase);
  843. chr = Regex.Replace(chr, @"<align=$1>$2</align>", @"[align=(?<x>[^]]*)](?<y>[^]]*)[/align]", RegexOptions.IgnoreCase);
  844. chr = Regex.Replace(chr, @"<marquee width=90% behavior=alternate scrollamount=3>$1</marquee>", @"[fly](?<x>[^]]*)[/fly]", RegexOptions.IgnoreCase);
  845. chr = Regex.Replace(chr, @"<marquee scrollamount=3>$1</marquee>", @"[move](?<x>[^]]*)[/move]", RegexOptions.IgnoreCase);
  846. chr = Regex.Replace(chr, @"<table width=$1 style='filter:glow(color=$2, strength=$3)'>$4</table>", @"[glow=(?<x>[^]]*),(?<y>[^]]*),(?<z>[^]]*)](?<w>[^]]*)[/glow]", RegexOptions.IgnoreCase);
  847. chr = Regex.Replace(chr, @"<table width=$1 style='filter:shadow(color=$2, strength=$3)'>$4</table>", @"[shadow=(?<x>[^]]*),(?<y>[^]]*),(?<z>[^]]*)](?<w>[^]]*)[/shadow]", RegexOptions.IgnoreCase);
  848. chr = Regex.Replace(chr, @"<b>$1</b>", @"[b](?<x>[^]]*)[/b]", RegexOptions.IgnoreCase);
  849. chr = Regex.Replace(chr, @"<i>$1</i>", @"[i](?<x>[^]]*)[/i]", RegexOptions.IgnoreCase);
  850. chr = Regex.Replace(chr, @"<u>$1</u>", @"[u](?<x>[^]]*)[/u]", RegexOptions.IgnoreCase);
  851. chr = Regex.Replace(chr, @"<pre id=code><font size=1 face='Verdana, Arial' id=code>$1</font id=code></pre id=code>", @"[code](?<x>[^]]*)[/code]", RegexOptions.IgnoreCase);
  852. chr = Regex.Replace(chr, @"<ul>$1</ul>", @"[list](?<x>[^]]*)[/list]", RegexOptions.IgnoreCase);
  853. chr = Regex.Replace(chr, @"<ol type=1>$1</ol id=1>", @"[list=1](?<x>[^]]*)[/list]", RegexOptions.IgnoreCase);
  854. chr = Regex.Replace(chr, @"<ol type=a>$1</ol id=a>", @"[list=a](?<x>[^]]*)[/list]", RegexOptions.IgnoreCase);
  855. chr = Regex.Replace(chr, @"<li>$1</li>", @"[*](?<x>[^]]*)[/*]", RegexOptions.IgnoreCase);
  856. chr = Regex.Replace(chr, @"<center>—— 以下是引用 ——<table border='1' width='80%' cellpadding='10' cellspacing='0' ><tr><td>$1</td></tr></table></center>", @"[quote](?<x>.*)[/quote]", RegexOptions.IgnoreCase);
  857. return chr;
  858. }
  859. /// <summary>
  860. /// Html转UBB
  861. /// </summary>
  862. /// <param name="chr">HTML代码</param>
  863. /// <returns>UBB代码</returns>
  864. public static async Task<string> HtmltoUBBAsync(this string chr) => await Task.Run(() => HtmltoUBB(chr));
  865. #endregion
  866. #region 数字互转
  867. /// <summary>
  868. /// 字符串转int
  869. /// </summary>
  870. /// <param name="s">源字符串</param>
  871. /// <returns>int类型的数字</returns>
  872. public static int ToInt32(this string s)
  873. {
  874. bool b = int.TryParse(s, out int result);
  875. return result;
  876. }
  877. /// <summary>
  878. /// 字符串转long
  879. /// </summary>
  880. /// <param name="s">源字符串</param>
  881. /// <returns>int类型的数字</returns>
  882. public static long ToInt64(this string s)
  883. {
  884. bool b = long.TryParse(s, out var result);
  885. return result;
  886. }
  887. /// <summary>
  888. /// 字符串转double
  889. /// </summary>
  890. /// <param name="s">源字符串</param>
  891. /// <returns>double类型的数据</returns>
  892. public static double ToDouble(this string s)
  893. {
  894. bool b = double.TryParse(s, out var result);
  895. return result;
  896. }
  897. /// <summary>
  898. /// 字符串转decimal
  899. /// </summary>
  900. /// <param name="s">源字符串</param>
  901. /// <returns>int类型的数字</returns>
  902. public static decimal ToDecimal(this string s)
  903. {
  904. var b = decimal.TryParse(s, out var result);
  905. return result;
  906. }
  907. /// <summary>
  908. /// 字符串转decimal
  909. /// </summary>
  910. /// <param name="s">源字符串</param>
  911. /// <returns>int类型的数字</returns>
  912. public static decimal ToDecimal(this double s)
  913. {
  914. return new decimal(s);
  915. }
  916. /// <summary>
  917. /// 字符串转double
  918. /// </summary>
  919. /// <param name="s">源字符串</param>
  920. /// <returns>double类型的数据</returns>
  921. public static double ToDouble(this decimal s)
  922. {
  923. return (double)s;
  924. }
  925. /// <summary>
  926. /// 将double转换成int
  927. /// </summary>
  928. /// <param name="num">double类型</param>
  929. /// <returns>int类型</returns>
  930. public static int ToInt32(this double num)
  931. {
  932. return (int)Math.Floor(num);
  933. }
  934. /// <summary>
  935. /// 将double转换成int
  936. /// </summary>
  937. /// <param name="num">double类型</param>
  938. /// <returns>int类型</returns>
  939. public static int ToInt32(this decimal num)
  940. {
  941. return (int)Math.Floor(num);
  942. }
  943. /// <summary>
  944. /// 将int转换成double
  945. /// </summary>
  946. /// <param name="num">int类型</param>
  947. /// <returns>int类型</returns>
  948. public static double ToDouble(this int num)
  949. {
  950. return num * 1.0;
  951. }
  952. /// <summary>
  953. /// 将int转换成decimal
  954. /// </summary>
  955. /// <param name="num">int类型</param>
  956. /// <returns>int类型</returns>
  957. public static decimal ToDecimal(this int num)
  958. {
  959. return (decimal)(num * 1.0);
  960. }
  961. #endregion
  962. #region 检测字符串中是否包含列表中的关键词
  963. /// <summary>
  964. /// 检测字符串中是否包含列表中的关键词
  965. /// </summary>
  966. /// <param name="s">源字符串</param>
  967. /// <param name="keys">关键词列表</param>
  968. /// <param name="ignoreCase">忽略大小写</param>
  969. /// <returns></returns>
  970. public static bool Contains(this string s, IEnumerable<string> keys, bool ignoreCase = true)
  971. {
  972. if (ignoreCase)
  973. {
  974. return Regex.IsMatch(s.ToLower(), string.Join("|", keys).ToLower(), RegexOptions.Compiled);
  975. }
  976. return Regex.IsMatch(s, string.Join("|", keys), RegexOptions.Compiled);
  977. }
  978. #endregion
  979. #region 匹配Email
  980. /// <summary>
  981. /// 匹配Email
  982. /// </summary>
  983. /// <param name="s">源字符串</param>
  984. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  985. /// <returns>匹配对象</returns>
  986. public static Match MatchEmail(this string s, out bool isMatch)
  987. {
  988. Match match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  989. isMatch = match.Success;
  990. return isMatch ? match : null;
  991. }
  992. /// <summary>
  993. /// 匹配Email
  994. /// </summary>
  995. /// <param name="s">源字符串</param>
  996. /// <returns>是否匹配成功</returns>
  997. public static bool MatchEmail(this string s)
  998. {
  999. MatchEmail(s, out bool success);
  1000. return success;
  1001. }
  1002. #endregion
  1003. #region 匹配完整的URL
  1004. /// <summary>
  1005. /// 匹配完整格式的URL
  1006. /// </summary>
  1007. /// <param name="s">源字符串</param>
  1008. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  1009. /// <returns>匹配对象</returns>
  1010. public static Uri MatchUrl(this string s, out bool isMatch)
  1011. {
  1012. try
  1013. {
  1014. isMatch = true;
  1015. return new Uri(s);
  1016. }
  1017. catch
  1018. {
  1019. isMatch = false;
  1020. return null;
  1021. }
  1022. }
  1023. /// <summary>
  1024. /// 匹配完整格式的URL
  1025. /// </summary>
  1026. /// <param name="s">源字符串</param>
  1027. /// <returns>是否匹配成功</returns>
  1028. public static bool MatchUrl(this string s)
  1029. {
  1030. MatchUrl(s, out var isMatch);
  1031. return isMatch;
  1032. }
  1033. #endregion
  1034. #region 权威校验身份证号码
  1035. /// <summary>
  1036. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  1037. /// </summary>
  1038. /// <param name="s">源字符串</param>
  1039. /// <returns>是否匹配成功</returns>
  1040. public static bool MatchIdentifyCard(this string s)
  1041. {
  1042. if (s.Length == 18)
  1043. {
  1044. if (long.TryParse(s.Remove(17), out var n) == false || n < Math.Pow(10, 16) || long.TryParse(s.Replace('x', '0').Replace('X', '0'), out n) == false)
  1045. {
  1046. return false; //数字验证
  1047. }
  1048. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  1049. if (address.IndexOf(s.Remove(2), StringComparison.Ordinal) == -1)
  1050. {
  1051. return false; //省份验证
  1052. }
  1053. string birth = s.Substring(6, 8).Insert(6, "-").Insert(4, "-");
  1054. DateTime time;
  1055. if (!DateTime.TryParse(birth, out time))
  1056. {
  1057. return false; //生日验证
  1058. }
  1059. string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
  1060. string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
  1061. char[] ai = s.Remove(17).ToCharArray();
  1062. int sum = 0;
  1063. for (int i = 0; i < 17; i++)
  1064. {
  1065. sum += wi[i].ToInt32() * ai[i].ToString().ToInt32();
  1066. }
  1067. int y;
  1068. Math.DivRem(sum, 11, out y);
  1069. if (arrVarifyCode[y] != s.Substring(17, 1).ToLower())
  1070. {
  1071. return false; //校验码验证
  1072. }
  1073. return true; //符合GB11643-1999标准
  1074. }
  1075. if (s.Length == 15)
  1076. {
  1077. if (long.TryParse(s, out var n) == false || n < Math.Pow(10, 14))
  1078. {
  1079. return false; //数字验证
  1080. }
  1081. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  1082. if (address.IndexOf(s.Remove(2), StringComparison.Ordinal) == -1)
  1083. {
  1084. return false; //省份验证
  1085. }
  1086. string birth = s.Substring(6, 6).Insert(4, "-").Insert(2, "-");
  1087. if (DateTime.TryParse(birth, out _) == false)
  1088. {
  1089. return false; //生日验证
  1090. }
  1091. return true;
  1092. }
  1093. return false;
  1094. }
  1095. #endregion
  1096. #region 校验IP地址的合法性
  1097. /// <summary>
  1098. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  1099. /// </summary>
  1100. /// <param name="s">源字符串</param>
  1101. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  1102. /// <returns>匹配对象</returns>
  1103. public static Match MatchInetAddress(this string s, out bool isMatch)
  1104. {
  1105. Match match;
  1106. if (s.Contains(":"))
  1107. {
  1108. //IPv6
  1109. match = Regex.Match(s, @"^([\da-fA-F]{0,4}:){1,7}[\da-fA-F]{1,4}$");
  1110. isMatch = match.Success;
  1111. }
  1112. else
  1113. {
  1114. //IPv4
  1115. match = Regex.Match(s, @"^(\d+)\.(\d+)\.(\d+)\.(\d+)$");
  1116. isMatch = match.Success;
  1117. foreach (Group m in match.Groups)
  1118. {
  1119. if (m.Value.ToInt32() < 0 || m.Value.ToInt32() > 255)
  1120. {
  1121. isMatch = false;
  1122. break;
  1123. }
  1124. }
  1125. }
  1126. return isMatch ? match : null;
  1127. }
  1128. /// <summary>
  1129. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  1130. /// </summary>
  1131. /// <param name="s">源字符串</param>
  1132. /// <returns>是否匹配成功</returns>
  1133. public static bool MatchInetAddress(this string s)
  1134. {
  1135. MatchInetAddress(s, out bool success);
  1136. return success;
  1137. }
  1138. #endregion
  1139. #region 校验手机号码的正确性
  1140. /// <summary>
  1141. /// 匹配手机号码
  1142. /// </summary>
  1143. /// <param name="s">源字符串</param>
  1144. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  1145. /// <returns>匹配对象</returns>
  1146. public static Match MatchPhoneNumber(this string s, out bool isMatch)
  1147. {
  1148. 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}$");
  1149. isMatch = match.Success;
  1150. return isMatch ? match : null;
  1151. }
  1152. /// <summary>
  1153. /// 匹配手机号码
  1154. /// </summary>
  1155. /// <param name="s">源字符串</param>
  1156. /// <returns>是否匹配成功</returns>
  1157. public static bool MatchPhoneNumber(this string s)
  1158. {
  1159. MatchPhoneNumber(s, out bool success);
  1160. return success;
  1161. }
  1162. #endregion
  1163. /// <summary>
  1164. /// 严格比较两个对象是否是同一对象
  1165. /// </summary>
  1166. /// <param name="_this">自己</param>
  1167. /// <param name="o">需要比较的对象</param>
  1168. /// <returns>是否同一对象</returns>
  1169. public new static bool ReferenceEquals(this object _this, object o) => object.ReferenceEquals(_this, o);
  1170. /// <summary>
  1171. /// 判断字符串是否为空
  1172. /// </summary>
  1173. /// <param name="s"></param>
  1174. /// <returns></returns>
  1175. public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s);
  1176. /// <summary>
  1177. /// 类型直转
  1178. /// </summary>
  1179. /// <typeparam name="T"></typeparam>
  1180. /// <param name="value"></param>
  1181. /// <returns></returns>
  1182. public static T To<T>(this IConvertible value)
  1183. {
  1184. try
  1185. {
  1186. return (T)Convert.ChangeType(value, typeof(T));
  1187. }
  1188. catch
  1189. {
  1190. return default(T);
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// 字符串转时间
  1195. /// </summary>
  1196. /// <param name="value"></param>
  1197. /// <returns></returns>
  1198. public static DateTime ToDateTime(this string value)
  1199. {
  1200. DateTime.TryParse(value, out var result);
  1201. return result;
  1202. }
  1203. /// <summary>
  1204. /// 字符串转Guid
  1205. /// </summary>
  1206. /// <param name="s"></param>
  1207. /// <returns></returns>
  1208. public static Guid ToGuid(this string s)
  1209. {
  1210. return Guid.Parse(s);
  1211. }
  1212. /// <summary>
  1213. /// 根据正则替换
  1214. /// </summary>
  1215. /// <param name="input"></param>
  1216. /// <param name="regex">正则表达式</param>
  1217. /// <param name="replacement">新内容</param>
  1218. /// <returns></returns>
  1219. public static string Replace(this string input, Regex regex, string replacement)
  1220. {
  1221. return regex.Replace(input, replacement);
  1222. }
  1223. /// <summary>
  1224. /// 生成唯一短字符串
  1225. /// </summary>
  1226. /// <param name="str"></param>
  1227. /// <param name="chars">可用字符数数量,0-9,a-z,A-Z</param>
  1228. /// <returns></returns>
  1229. public static string CreateShortToken(this string str, byte chars = 36)
  1230. {
  1231. var nf = new NumberFormater(chars);
  1232. return nf.ToString((DateTime.Now.Ticks - 630822816000000000) * 100 + Stopwatch.GetTimestamp() % 100);
  1233. }
  1234. /// <summary>
  1235. /// 十进制转任意进制
  1236. /// </summary>
  1237. /// <param name="num"></param>
  1238. /// <param name="bin">进制</param>
  1239. /// <returns></returns>
  1240. public static string ToBinary(this long num, int bin)
  1241. {
  1242. var nf = new NumberFormater(bin);
  1243. return nf.ToString(num);
  1244. }
  1245. /// <summary>
  1246. /// 十进制转任意进制
  1247. /// </summary>
  1248. /// <param name="num"></param>
  1249. /// <param name="bin">进制</param>
  1250. /// <returns></returns>
  1251. public static string ToBinary(this int num, int bin)
  1252. {
  1253. var nf = new NumberFormater(bin);
  1254. return nf.ToString(num);
  1255. }
  1256. /// <summary>
  1257. /// 按字段去重
  1258. /// </summary>
  1259. /// <typeparam name="TSource"></typeparam>
  1260. /// <typeparam name="TKey"></typeparam>
  1261. /// <param name="source"></param>
  1262. /// <param name="keySelector"></param>
  1263. /// <returns></returns>
  1264. public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  1265. {
  1266. HashSet<TKey> hash = new HashSet<TKey>();
  1267. return source.Where(p => hash.Add(keySelector(p)));
  1268. }
  1269. /// <summary>
  1270. /// 将小数截断为8位
  1271. /// </summary>
  1272. /// <param name="num"></param>
  1273. /// <returns></returns>
  1274. public static double Digits8(this double num)
  1275. {
  1276. return (long)(num * 1E+8) * 1e-8;
  1277. }
  1278. /// <summary>
  1279. /// 判断IP地址在不在某个IP地址段
  1280. /// </summary>
  1281. /// <param name="input">需要判断的IP地址</param>
  1282. /// <param name="begin">起始地址</param>
  1283. /// <param name="ends">结束地址</param>
  1284. /// <returns></returns>
  1285. public static bool IpAddressInRange(this string input, string begin, string ends)
  1286. {
  1287. uint current = IPToID(input);
  1288. return current >= IPToID(begin) && current <= IPToID(ends);
  1289. }
  1290. /// <summary>
  1291. /// IP地址转换成数字
  1292. /// </summary>
  1293. /// <param name="addr">IP地址</param>
  1294. /// <returns>数字,输入无效IP地址返回0</returns>
  1295. private static uint IPToID(string addr)
  1296. {
  1297. if (!IPAddress.TryParse(addr, out var ip))
  1298. {
  1299. return 0;
  1300. }
  1301. byte[] bInt = ip.GetAddressBytes();
  1302. if (BitConverter.IsLittleEndian)
  1303. {
  1304. Array.Reverse(bInt);
  1305. }
  1306. return BitConverter.ToUInt32(bInt, 0);
  1307. }
  1308. /// <summary>
  1309. /// 判断IP是否是私有地址
  1310. /// </summary>
  1311. /// <param name="myIPAddress"></param>
  1312. /// <returns></returns>
  1313. public static bool IsPrivateIP(this IPAddress myIPAddress)
  1314. {
  1315. if (IPAddress.IsLoopback(myIPAddress)) return true;
  1316. if (myIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  1317. {
  1318. byte[] ipBytes = myIPAddress.GetAddressBytes();
  1319. // 10.0.0.0/24
  1320. if (ipBytes[0] == 10)
  1321. {
  1322. return true;
  1323. }
  1324. // 169.254.0.0/16
  1325. if (ipBytes[0] == 169 && ipBytes[1] == 254)
  1326. {
  1327. return true;
  1328. }
  1329. // 172.16.0.0/16
  1330. if (ipBytes[0] == 172 && ipBytes[1] == 16)
  1331. {
  1332. return true;
  1333. }
  1334. // 192.168.0.0/16
  1335. if (ipBytes[0] == 192 && ipBytes[1] == 168)
  1336. {
  1337. return true;
  1338. }
  1339. }
  1340. return false;
  1341. }
  1342. /// <summary>
  1343. /// 判断IP是否是私有地址
  1344. /// </summary>
  1345. /// <param name="ip"></param>
  1346. /// <returns></returns>
  1347. public static bool IsPrivateIP(this string ip)
  1348. {
  1349. if (MatchInetAddress(ip))
  1350. {
  1351. return IsPrivateIP(IPAddress.Parse(ip));
  1352. }
  1353. throw new ArgumentException("不是一个合法的ip地址");
  1354. }
  1355. /// <summary>
  1356. /// 判断url是否是外部地址
  1357. /// </summary>
  1358. /// <param name="url"></param>
  1359. /// <returns></returns>
  1360. public static bool IsExternalAddress(this string url)
  1361. {
  1362. var uri = new Uri(url);
  1363. switch (uri.HostNameType)
  1364. {
  1365. case UriHostNameType.Dns:
  1366. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  1367. foreach (IPAddress ipAddress in ipHostEntry.AddressList)
  1368. {
  1369. if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  1370. {
  1371. if (!ipAddress.IsPrivateIP())
  1372. {
  1373. return true;
  1374. }
  1375. }
  1376. }
  1377. break;
  1378. case UriHostNameType.IPv4:
  1379. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  1380. }
  1381. return false;
  1382. }
  1383. /// <summary>
  1384. /// 生成真正的随机数
  1385. /// </summary>
  1386. /// <param name="r"></param>
  1387. /// <param name="seed"></param>
  1388. /// <returns></returns>
  1389. public static int StrictNext(this Random r, int seed = int.MaxValue)
  1390. {
  1391. return new Random((int)Stopwatch.GetTimestamp()).Next(seed);
  1392. }
  1393. /// <summary>
  1394. /// 产生正态分布的随机数
  1395. /// </summary>
  1396. /// <param name="rand"></param>
  1397. /// <param name="mean">均值</param>
  1398. /// <param name="stdDev">方差</param>
  1399. /// <returns></returns>
  1400. public static double NextGauss(this Random rand, double mean, double stdDev)
  1401. {
  1402. double u1 = 1.0 - rand.NextDouble();
  1403. double u2 = 1.0 - rand.NextDouble();
  1404. double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
  1405. return mean + stdDev * randStdNormal;
  1406. }
  1407. }
  1408. }