RegHelper.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace CSharpUtil.Text
  7. {
  8. /// <summary>
  9. /// 正则表达式工具类,集合了一些常见表达式. 内建了表达式缓存. 避免每次使用重新编译.
  10. /// author:gwang
  11. /// </summary>
  12. public class RegHelper
  13. {
  14. #region ' 构造函数 '
  15. private RegHelper()
  16. {
  17. }
  18. static Dictionary<string, Regex> cache = new Dictionary<string, Regex>();
  19. static Regex GetRegex(string name, string patrn, RegexOptions opts = RegexOptions.None)
  20. {
  21. if (!cache.ContainsKey(name))
  22. {
  23. cache.Add(name, new Regex(patrn, opts));
  24. }
  25. return cache[name];
  26. }
  27. #endregion
  28. #region ' 方法 '
  29. /// <summary>
  30. /// 校验登录名:只能输入5-20个以字母开头、可带数字、“_”、“.”的字串
  31. /// </summary>
  32. /// <param name="s"></param>
  33. /// <returns></returns>
  34. static public bool isRegisterUserName(string s)
  35. {
  36. const string rname = "RegisterUserName";
  37. const string patrn = @"^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$";
  38. Regex re = GetRegex(rname, patrn);
  39. return re.IsMatch(s);
  40. }
  41. /// <summary>
  42. /// 校验玩家昵称: 只能输入5到10个汉字或者数字、英文字母
  43. /// </summary>
  44. /// <param name="s"></param>
  45. /// <returns></returns>
  46. static public bool isNickName(string s)
  47. {
  48. const string rname = "NickName";
  49. const string patrn = @"^[a-zA-Z0-9_\u4e00-\u9fa5]{4,9}$";
  50. Regex re = GetRegex(rname, patrn);
  51. return re.IsMatch(s);
  52. }
  53. /// <summary>
  54. /// 电话号码-固机(010/0311-1234567(8))
  55. /// </summary>
  56. /// <param name="s"></param>
  57. /// <returns></returns>
  58. static public bool isTellNumber(string s)
  59. {
  60. const string rname = "TellNumber";
  61. const string patrn = @"^((d{3,4})|d{3,4}-)?d{7,8}$";
  62. Regex re = GetRegex(rname, patrn);
  63. return re.IsMatch(s);
  64. }
  65. /// <summary>
  66. /// 电话号码-手机号(国内)
  67. /// </summary>
  68. /// <param name="s"></param>
  69. /// <returns></returns>
  70. static public bool isCellPhoneNumber(string s)
  71. {
  72. const string rname = "TellNumber";
  73. const string patrn = @"^0?(13|14|15|18)[0-9]{9}$";
  74. Regex re = GetRegex(rname, patrn);
  75. return re.IsMatch(s);
  76. }
  77. #endregion
  78. }
  79. }