颐和api

RegexHelper.cs 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Collections.Generic;
  2. using System.Text.RegularExpressions;
  3. namespace MadRunFabric.Common
  4. {
  5. /// <summary>
  6. /// 正则表达式公共类
  7. /// </summary>
  8. public class RegexHelper
  9. {
  10. /// <summary>
  11. /// 检查是否匹配
  12. /// </summary>
  13. /// <param name="str"></param>
  14. /// <param name="pattern"></param>
  15. /// <param name="options"></param>
  16. /// <returns></returns>
  17. public static bool IsMatch(string str, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
  18. {
  19. return Regex.IsMatch(str, pattern, options);
  20. }
  21. /// <summary>
  22. /// 获取匹配对象
  23. /// </summary>
  24. /// <param name="str"></param>
  25. /// <param name="pattern"></param>
  26. /// <param name="options"></param>
  27. /// <returns></returns>
  28. public static Match GetMatch(string str, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
  29. {
  30. return Regex.Match(str, pattern, options);
  31. }
  32. /// <summary>
  33. /// 从字符串中找到匹配的字符
  34. /// </summary>
  35. /// <param name="str">原始字符</param>
  36. /// <param name="pattern">正则</param>
  37. /// <param name="spliter">分隔符</param>
  38. /// <returns></returns>
  39. public static List<Match> FindMatchs(string str, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
  40. {
  41. var list = new List<Match>();
  42. var matchs = Regex.Matches(str, pattern, options);
  43. foreach (Match matcher in matchs)
  44. {
  45. if (matcher == null || !matcher.Success) { continue; }
  46. list.Add(matcher);
  47. }
  48. return list;
  49. }
  50. /// <summary>
  51. /// 用正则替换
  52. /// </summary>
  53. /// <param name="str"></param>
  54. /// <param name="replacement"></param>
  55. /// <param name="pattern"></param>
  56. /// <returns></returns>
  57. public static string Replace(string str, string replacement, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
  58. {
  59. return Regex.Replace(str, pattern, replacement, options);
  60. }
  61. }
  62. }