RegexHelper.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Text.RegularExpressions;
  2. namespace Common
  3. {
  4. /// <summary>
  5. /// 操作正则表达式的公共类
  6. /// </summary>
  7. public class RegexHelper
  8. {
  9. #region 验证输入字符串是否与模式字符串匹配
  10. /// <summary>
  11. /// 验证输入字符串是否与模式字符串匹配,匹配返回true
  12. /// </summary>
  13. /// <param name="input">输入的字符串</param>
  14. /// <param name="pattern">模式字符串</param>
  15. /// <param name="options">筛选条件</param>
  16. public static bool IsMatch(string input, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
  17. {
  18. return Regex.IsMatch(input, pattern, options);
  19. }
  20. /// <summary>
  21. /// 获取第一个匹配到的字符串
  22. /// </summary>
  23. /// <param name="input"></param>
  24. /// <param name="pattern"></param>
  25. /// <param name="options"></param>
  26. /// <returns></returns>
  27. public static string GetMatchResult(string input, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
  28. {
  29. if (IsMatch(input, pattern))
  30. {
  31. Regex regex = new Regex(pattern, options);
  32. MatchCollection collection = regex.Matches(input);
  33. GroupCollection groupCollection = collection[0].Groups;
  34. return groupCollection[0].Value;
  35. }
  36. return "";
  37. }
  38. #endregion
  39. }
  40. }