RegexHelper.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Collections.Generic;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. namespace Vinno.vCloud.Disk
  5. {
  6. public class RegexHelper
  7. {
  8. private RegexHelper(){}
  9. /// <summary>
  10. /// 正则表达式替换
  11. /// </summary>
  12. /// <param name="input"></param>
  13. /// <param name="pattern"></param>
  14. /// <param name="replacement"></param>
  15. /// <returns></returns>
  16. public static string Replace(string input,string pattern,string replacement)
  17. {
  18. StringBuilder stringBuilder = new StringBuilder(input);
  19. var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
  20. if (matches.Count > 0)
  21. {
  22. foreach (Match match in matches)
  23. {
  24. if (match.Success && !string.IsNullOrWhiteSpace(match.Value))
  25. {
  26. if (match.Groups.Count > 1)
  27. {
  28. stringBuilder.Replace(match.Groups[1].Value, replacement);
  29. }
  30. else
  31. {
  32. stringBuilder.Replace(match.Value, replacement);
  33. }
  34. }
  35. }
  36. }
  37. return stringBuilder.ToString();
  38. }
  39. public static string MatchSub(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
  40. {
  41. var match = Regex.Match(input, pattern, regexOptions);
  42. if (match.Success && match.Groups.Count>1)
  43. {
  44. return match.Groups[1].Value;
  45. }
  46. return string.Empty;
  47. }
  48. public static bool IsMatch(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
  49. {
  50. return Regex.IsMatch(input, pattern, regexOptions);
  51. }
  52. }
  53. }