Extensions.cs 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  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. 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. 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. 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. 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. /// <returns></returns>
  969. public static bool Contains(this string s, string[] keys) => Regex.IsMatch(s.ToLower(), string.Join("|", keys).ToLower());
  970. #endregion
  971. #region 匹配Email
  972. /// <summary>
  973. /// 匹配Email
  974. /// </summary>
  975. /// <param name="s">源字符串</param>
  976. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  977. /// <returns>匹配对象</returns>
  978. public static Match MatchEmail(this string s, out bool isMatch)
  979. {
  980. Match match = Regex.Match(s, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  981. isMatch = match.Success;
  982. return isMatch ? match : null;
  983. }
  984. /// <summary>
  985. /// 匹配Email
  986. /// </summary>
  987. /// <param name="s">源字符串</param>
  988. /// <returns>是否匹配成功</returns>
  989. public static bool MatchEmail(this string s)
  990. {
  991. MatchEmail(s, out bool success);
  992. return success;
  993. }
  994. #endregion
  995. #region 匹配完整的URL
  996. /// <summary>
  997. /// 匹配完整格式的URL,支持以下格式的URL,支持中文域名:<br/>
  998. /// 支持不带协议名的网址,支持自适应协议的网址,支持完整路径,支持查询参数,支持锚点,支持锚点查询参数,支持16进制编码<br/>
  999. /// www.baidu.com <br/>
  1000. /// www.baidu.com <br/>
  1001. /// baidu.com <br/>
  1002. /// //www.baidu.com <br/>
  1003. /// http://www.baidu.com <br/>
  1004. /// https://www.baidu.com <br/>
  1005. /// https://baidu.com <br/>
  1006. /// ftp://baidu.com <br/>
  1007. /// ftp://baidu.com/abc/def <br/>
  1008. /// ftp://admin:[email protected] <br/>
  1009. /// ftp://admin:[email protected]/abc/def <br/>
  1010. /// https://baidu.com:8080 <br/>
  1011. /// https://baidu.com/abc/def <br/>
  1012. /// https://baidu.com:8080/abc/def <br/>
  1013. /// https://baidu.com:8080/abc/def/hhh.html <br/>
  1014. /// https://baidu.com:8080/abc/def/hhh.html?s=www <br/>
  1015. /// https://baidu.com/abc/def/hhh.html?s=w@w{w}!s <br/>
  1016. /// https://baidu.com:8080/abc/def/hhh.html?s=www&amp;x=yy+y <br/>
  1017. /// https://baidu.com/abc/def/hhh.html?s=www&amp;x=yyy <br/>
  1018. /// https://baidu.com:8080/abc/def/hhh.html?s=www&amp;x=yyy#top <br/>
  1019. /// https://baidu.com:8080/abc/def/hi_jk-mn%ADF%AA/hhh.html?s=www&amp;x=yyy#top <br/>
  1020. /// https://baidu.com:8080/abc/def/hi_j+k-mn%ADF%AA?s=www&amp;x=yyy#top/aaa <br/>
  1021. /// https://baidu.com:8080/abc/def/hi_jk-mn%ADF%AA?s=www&amp;x=yyy#top/aaa/bbb/ccc <br/>
  1022. /// http://music.163.com/#/my/m/music/empty <br/>
  1023. /// http://music.163.com/abc/#/my/m/music/empty <br/>
  1024. /// http://music.163.com/def/hhh.html?s=www&amp;x=yyy#/my/m/music/empty <br/>
  1025. /// http://music.163.com/def/hhh.html?s=www&amp;x=yyy/#/my/m/music/empty <br/>
  1026. /// http://music.163.com/#/search/m/?%23%2Fmy%2Fm%2Fmusic%2Fempty=&amp;s=fade&amp;type=1!k <br/>
  1027. /// </summary>
  1028. /// <param name="s">源字符串</param>
  1029. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  1030. /// <returns>匹配对象</returns>
  1031. public static Match MatchUrl(this string s, out bool isMatch)
  1032. {
  1033. Match match = Regex.Match(s, @"^((\w*):?//)?([a-zA-Z0-9\-]{0,61}:?[a-zA-Z0-9\-]{0,61}@?)?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}(:(\d{1,5}))?(/([a-z0-9A-Z-_@{}!+%/]+(\.\w+)?)?(\?([a-z0-9A-Z-_@{}!+%]+=[a-z0-9A-Z-_@{}!+%]+&?)+)?(/?#[a-z0-9A-Z-_@{}!+%/]+)?(\?([a-z0-9A-Z-_@{}!+%]+=[a-z0-9A-Z-_@{}!+%]*&?)+)?)?$");
  1034. isMatch = match.Success;
  1035. return isMatch ? match : null;
  1036. }
  1037. /// <summary>
  1038. /// 匹配完整格式的URL,支持以下格式的URL,支持中文域名:<br/>
  1039. /// 支持不带协议名的网址,支持自适应协议的网址,支持完整路径,支持查询参数,支持锚点,支持锚点查询参数,支持16进制编码<br/>
  1040. /// www.baidu.com <br/>
  1041. /// www.baidu.com <br/>
  1042. /// baidu.com <br/>
  1043. /// //www.baidu.com <br/>
  1044. /// http://www.baidu.com <br/>
  1045. /// https://www.baidu.com <br/>
  1046. /// https://baidu.com <br/>
  1047. /// ftp://baidu.com <br/>
  1048. /// ftp://baidu.com/abc/def <br/>
  1049. /// ftp://admin:[email protected] <br/>
  1050. /// ftp://admin:[email protected]/abc/def <br/>
  1051. /// https://baidu.com:8080 <br/>
  1052. /// https://baidu.com/abc/def <br/>
  1053. /// https://baidu.com:8080/abc/def <br/>
  1054. /// https://baidu.com:8080/abc/def/hhh.html <br/>
  1055. /// https://baidu.com:8080/abc/def/hhh.html?s=www <br/>
  1056. /// https://baidu.com/abc/def/hhh.html?s=w@w{w}!s <br/>
  1057. /// https://baidu.com:8080/abc/def/hhh.html?s=www&amp;x=yy+y <br/>
  1058. /// https://baidu.com/abc/def/hhh.html?s=www&amp;x=yyy <br/>
  1059. /// https://baidu.com:8080/abc/def/hhh.html?s=www&amp;x=yyy#top <br/>
  1060. /// https://baidu.com:8080/abc/def/hi_jk-mn%ADF%AA/hhh.html?s=www&amp;x=yyy#top <br/>
  1061. /// https://baidu.com:8080/abc/def/hi_j+k-mn%ADF%AA?s=www&amp;x=yyy#top/aaa <br/>
  1062. /// https://baidu.com:8080/abc/def/hi_jk-mn%ADF%AA?s=www&amp;x=yyy#top/aaa/bbb/ccc <br/>
  1063. /// http://music.163.com/#/my/m/music/empty <br/>
  1064. /// http://music.163.com/abc/#/my/m/music/empty <br/>
  1065. /// http://music.163.com/def/hhh.html?s=www&amp;x=yyy#/my/m/music/empty <br/>
  1066. /// http://music.163.com/def/hhh.html?s=www&amp;x=yyy/#/my/m/music/empty <br/>
  1067. /// http://music.163.com/#/search/m/?%23%2Fmy%2Fm%2Fmusic%2Fempty=&amp;s=fade&amp;type=1!k <br/>
  1068. /// </summary>
  1069. /// <param name="s">源字符串</param>
  1070. /// <returns>是否匹配成功</returns>
  1071. public static bool MatchUrl(this string s)
  1072. {
  1073. MatchUrl(s, out bool success);
  1074. return success;
  1075. }
  1076. #endregion
  1077. #region 权威校验身份证号码
  1078. /// <summary>
  1079. /// 根据GB11643-1999标准权威校验中国身份证号码的合法性
  1080. /// </summary>
  1081. /// <param name="s">源字符串</param>
  1082. /// <returns>是否匹配成功</returns>
  1083. public static bool MatchIdentifyCard(this string s)
  1084. {
  1085. if (s.Length == 18)
  1086. {
  1087. 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)
  1088. {
  1089. return false; //数字验证
  1090. }
  1091. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  1092. if (address.IndexOf(s.Remove(2), StringComparison.Ordinal) == -1)
  1093. {
  1094. return false; //省份验证
  1095. }
  1096. string birth = s.Substring(6, 8).Insert(6, "-").Insert(4, "-");
  1097. DateTime time;
  1098. if (!DateTime.TryParse(birth, out time))
  1099. {
  1100. return false; //生日验证
  1101. }
  1102. string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
  1103. string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
  1104. char[] ai = s.Remove(17).ToCharArray();
  1105. int sum = 0;
  1106. for (int i = 0; i < 17; i++)
  1107. {
  1108. sum += wi[i].ToInt32() * ai[i].ToString().ToInt32();
  1109. }
  1110. int y;
  1111. Math.DivRem(sum, 11, out y);
  1112. if (arrVarifyCode[y] != s.Substring(17, 1).ToLower())
  1113. {
  1114. return false; //校验码验证
  1115. }
  1116. return true; //符合GB11643-1999标准
  1117. }
  1118. if (s.Length == 15)
  1119. {
  1120. if (long.TryParse(s, out var n) == false || n < Math.Pow(10, 14))
  1121. {
  1122. return false; //数字验证
  1123. }
  1124. string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
  1125. if (address.IndexOf(s.Remove(2), StringComparison.Ordinal) == -1)
  1126. {
  1127. return false; //省份验证
  1128. }
  1129. string birth = s.Substring(6, 6).Insert(4, "-").Insert(2, "-");
  1130. if (DateTime.TryParse(birth, out _) == false)
  1131. {
  1132. return false; //生日验证
  1133. }
  1134. return true;
  1135. }
  1136. return false;
  1137. }
  1138. #endregion
  1139. #region 校验IP地址的合法性
  1140. /// <summary>
  1141. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  1142. /// </summary>
  1143. /// <param name="s">源字符串</param>
  1144. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  1145. /// <returns>匹配对象</returns>
  1146. public static Match MatchInetAddress(this string s, out bool isMatch)
  1147. {
  1148. Match match;
  1149. if (s.Contains(":"))
  1150. {
  1151. //IPv6
  1152. match = Regex.Match(s, @"^([\da-fA-F]{0,4}:){1,7}[\da-fA-F]{1,4}$");
  1153. isMatch = match.Success;
  1154. }
  1155. else
  1156. {
  1157. //IPv4
  1158. match = Regex.Match(s, @"^(\d+)\.(\d+)\.(\d+)\.(\d+)$");
  1159. isMatch = match.Success;
  1160. foreach (Group m in match.Groups)
  1161. {
  1162. if (m.Value.ToInt32() < 0 || m.Value.ToInt32() > 255)
  1163. {
  1164. isMatch = false;
  1165. break;
  1166. }
  1167. }
  1168. }
  1169. return isMatch ? match : null;
  1170. }
  1171. /// <summary>
  1172. /// 校验IP地址的正确性,同时支持IPv4和IPv6
  1173. /// </summary>
  1174. /// <param name="s">源字符串</param>
  1175. /// <returns>是否匹配成功</returns>
  1176. public static bool MatchInetAddress(this string s)
  1177. {
  1178. MatchInetAddress(s, out bool success);
  1179. return success;
  1180. }
  1181. #endregion
  1182. #region 校验手机号码的正确性
  1183. /// <summary>
  1184. /// 匹配手机号码
  1185. /// </summary>
  1186. /// <param name="s">源字符串</param>
  1187. /// <param name="isMatch">是否匹配成功,若返回true,则会得到一个Match对象,否则为null</param>
  1188. /// <returns>匹配对象</returns>
  1189. public static Match MatchPhoneNumber(this string s, out bool isMatch)
  1190. {
  1191. Match match = Regex.Match(s, @"^((1[3,5,8][0-9])|(14[5,7])|(17[0,1,3,6,7,8])|(19[8,9]))\d{8}$");
  1192. isMatch = match.Success;
  1193. return isMatch ? match : null;
  1194. }
  1195. /// <summary>
  1196. /// 匹配手机号码
  1197. /// </summary>
  1198. /// <param name="s">源字符串</param>
  1199. /// <returns>是否匹配成功</returns>
  1200. public static bool MatchPhoneNumber(this string s)
  1201. {
  1202. MatchPhoneNumber(s, out bool success);
  1203. return success;
  1204. }
  1205. #endregion
  1206. /// <summary>
  1207. /// 严格比较两个对象是否是同一对象
  1208. /// </summary>
  1209. /// <param name="_this">自己</param>
  1210. /// <param name="o">需要比较的对象</param>
  1211. /// <returns>是否同一对象</returns>
  1212. public new static bool ReferenceEquals(this object _this, object o) => object.ReferenceEquals(_this, o);
  1213. /// <summary>
  1214. /// 判断字符串是否为空
  1215. /// </summary>
  1216. /// <param name="s"></param>
  1217. /// <returns></returns>
  1218. public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s);
  1219. /// <summary>
  1220. /// 类型直转
  1221. /// </summary>
  1222. /// <typeparam name="T"></typeparam>
  1223. /// <param name="value"></param>
  1224. /// <returns></returns>
  1225. public static T To<T>(this IConvertible value)
  1226. {
  1227. try
  1228. {
  1229. return (T)Convert.ChangeType(value, typeof(T));
  1230. }
  1231. catch
  1232. {
  1233. return default(T);
  1234. }
  1235. }
  1236. /// <summary>
  1237. /// 字符串转时间
  1238. /// </summary>
  1239. /// <param name="value"></param>
  1240. /// <returns></returns>
  1241. public static DateTime ToDateTime(this string value)
  1242. {
  1243. DateTime.TryParse(value, out var result);
  1244. return result;
  1245. }
  1246. /// <summary>
  1247. /// 字符串转Guid
  1248. /// </summary>
  1249. /// <param name="s"></param>
  1250. /// <returns></returns>
  1251. public static Guid ToGuid(this string s)
  1252. {
  1253. return Guid.Parse(s);
  1254. }
  1255. /// <summary>
  1256. /// 根据正则替换
  1257. /// </summary>
  1258. /// <param name="input"></param>
  1259. /// <param name="regex">正则表达式</param>
  1260. /// <param name="replacement">新内容</param>
  1261. /// <returns></returns>
  1262. public static string Replace(this string input, Regex regex, string replacement)
  1263. {
  1264. return regex.Replace(input, replacement);
  1265. }
  1266. /// <summary>
  1267. /// 生成唯一短字符串
  1268. /// </summary>
  1269. /// <param name="str"></param>
  1270. /// <param name="length">生成的字符串长度,越长冲突的概率越小,默认长度为6,最小长度为5,最大长度为22</param>
  1271. /// <returns></returns>
  1272. public static string CreateShortToken(this string str, int length = 6)
  1273. {
  1274. var temp = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Trim('=');
  1275. if (length <= 22)
  1276. {
  1277. if (length < 5)
  1278. {
  1279. length = 5;
  1280. }
  1281. temp = temp.Substring(0, length);
  1282. }
  1283. return Regex.Replace(temp, @"\p{P}|\+", string.Empty);
  1284. }
  1285. /// <summary>
  1286. /// 生成唯一短字符串
  1287. /// </summary>
  1288. /// <param name="str"></param>
  1289. /// <returns></returns>
  1290. public static string CreateShortToken(this string str)
  1291. {
  1292. var nf = new NumberFormater(36);
  1293. return nf.ToString(Stopwatch.GetTimestamp());
  1294. }
  1295. /// <summary>
  1296. /// 按字段去重
  1297. /// </summary>
  1298. /// <typeparam name="TSource"></typeparam>
  1299. /// <typeparam name="TKey"></typeparam>
  1300. /// <param name="source"></param>
  1301. /// <param name="keySelector"></param>
  1302. /// <returns></returns>
  1303. public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  1304. {
  1305. HashSet<TKey> hash = new HashSet<TKey>();
  1306. return source.Where(p => hash.Add(keySelector(p)));
  1307. }
  1308. /// <summary>
  1309. /// 将小数截断为8位
  1310. /// </summary>
  1311. /// <param name="num"></param>
  1312. /// <returns></returns>
  1313. public static double Digits8(this double num)
  1314. {
  1315. return (long)(num * 1E+8) * 1e-8;
  1316. }
  1317. /// <summary>
  1318. /// 判断IP地址在不在某个IP地址段
  1319. /// </summary>
  1320. /// <param name="input">需要判断的IP地址</param>
  1321. /// <param name="begin">起始地址</param>
  1322. /// <param name="ends">结束地址</param>
  1323. /// <returns></returns>
  1324. public static bool IpAddressInRange(this string input, string begin, string ends)
  1325. {
  1326. if (input.MatchInetAddress() && begin.MatchInetAddress() && ends.MatchInetAddress())
  1327. {
  1328. string[] ipStarts = begin.Split('.');
  1329. string[] ipEnds = ends.Split('.');
  1330. string[] inputs = input.Split('.');
  1331. uint start = uint.Parse(ipStarts[0]) << 24 | uint.Parse(ipStarts[1]) << 16 | uint.Parse(ipStarts[2]) << 8 | uint.Parse(ipStarts[3]);
  1332. uint end = uint.Parse(ipEnds[0]) << 24 | uint.Parse(ipEnds[1]) << 16 | uint.Parse(ipEnds[2]) << 8 | uint.Parse(ipEnds[3]);
  1333. uint current = uint.Parse(inputs[0]) << 24 | uint.Parse(inputs[1]) << 16 | uint.Parse(inputs[2]) << 8 | uint.Parse(inputs[3]);
  1334. return current >= start && current <= end;
  1335. }
  1336. return false;
  1337. }
  1338. /// <summary>
  1339. /// 判断IP是否是私有地址
  1340. /// </summary>
  1341. /// <param name="myIPAddress"></param>
  1342. /// <returns></returns>
  1343. public static bool IsPrivateIP(this IPAddress myIPAddress)
  1344. {
  1345. if (IPAddress.IsLoopback(myIPAddress)) return true;
  1346. if (myIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  1347. {
  1348. byte[] ipBytes = myIPAddress.GetAddressBytes();
  1349. // 10.0.0.0/24
  1350. if (ipBytes[0] == 10)
  1351. {
  1352. return true;
  1353. }
  1354. // 169.254.0.0/16
  1355. if (ipBytes[0] == 169 && ipBytes[1] == 254)
  1356. {
  1357. return true;
  1358. }
  1359. // 172.16.0.0/16
  1360. if (ipBytes[0] == 172 && ipBytes[1] == 16)
  1361. {
  1362. return true;
  1363. }
  1364. // 192.168.0.0/16
  1365. if (ipBytes[0] == 192 && ipBytes[1] == 168)
  1366. {
  1367. return true;
  1368. }
  1369. }
  1370. return false;
  1371. }
  1372. /// <summary>
  1373. /// 判断IP是否是私有地址
  1374. /// </summary>
  1375. /// <param name="ip"></param>
  1376. /// <returns></returns>
  1377. public static bool IsPrivateIP(this string ip)
  1378. {
  1379. if (MatchInetAddress(ip))
  1380. {
  1381. return IsPrivateIP(IPAddress.Parse(ip));
  1382. }
  1383. throw new ArgumentException("不是一个合法的ip地址");
  1384. }
  1385. /// <summary>
  1386. /// 判断url是否是外部地址
  1387. /// </summary>
  1388. /// <param name="url"></param>
  1389. /// <returns></returns>
  1390. public static bool IsExternalAddress(this string url)
  1391. {
  1392. var uri = new Uri(url);
  1393. switch (uri.HostNameType)
  1394. {
  1395. case UriHostNameType.Dns:
  1396. var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
  1397. foreach (IPAddress ipAddress in ipHostEntry.AddressList)
  1398. {
  1399. if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  1400. {
  1401. if (!ipAddress.IsPrivateIP())
  1402. {
  1403. return true;
  1404. }
  1405. }
  1406. }
  1407. break;
  1408. case UriHostNameType.IPv4:
  1409. return !IPAddress.Parse(uri.DnsSafeHost).IsPrivateIP();
  1410. }
  1411. return false;
  1412. }
  1413. }
  1414. }