RegexHelper.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. namespace PackingPress.Common
  8. {
  9. public class RegexHelper
  10. {
  11. private RegexHelper(){}
  12. /// <summary>
  13. /// 正则表达式替换
  14. /// </summary>
  15. /// <param name="input"></param>
  16. /// <param name="pattern"></param>
  17. /// <param name="replacement"></param>
  18. /// <returns></returns>
  19. public static string Replace(string input, string pattern, string replacement)
  20. {
  21. StringBuilder stringBuilder = new StringBuilder(input);
  22. var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
  23. if (matches.Count > 0)
  24. {
  25. foreach (Match match in matches)
  26. {
  27. if (match.Success)
  28. {
  29. if (match.Groups.Count > 1)
  30. {
  31. stringBuilder.Replace(match.Groups[1].Value, replacement);
  32. }
  33. else
  34. {
  35. stringBuilder.Replace(match.Value, replacement);
  36. }
  37. }
  38. }
  39. }
  40. return stringBuilder.ToString();
  41. }
  42. public static string MatchSub(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
  43. {
  44. var match = Regex.Match(input, pattern, regexOptions);
  45. if (match.Success && match.Groups.Count > 1)
  46. {
  47. return match.Groups[1].Value;
  48. }
  49. return string.Empty;
  50. }
  51. public static List<string> MatchSubAll(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
  52. {
  53. List<string> matchesList = new List<string>();
  54. var matches = Regex.Matches(input, pattern, regexOptions);
  55. if (matches.Count > 1)
  56. {
  57. foreach (Match match in matches)
  58. {
  59. if (match.Success && match.Groups.Count > 1)
  60. {
  61. matchesList.Add(match.Groups[1].Value);
  62. }
  63. }
  64. }
  65. return matchesList;
  66. }
  67. public static bool IsMatch(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
  68. {
  69. return Regex.IsMatch(input, pattern, regexOptions);
  70. }
  71. }
  72. }