IsStrLegal.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System.Text.RegularExpressions;
  2. namespace MainForm
  3. {
  4. /// <summary>
  5. /// 判断字符串格式是否合法类
  6. /// </summary>
  7. class IsStrLegal
  8. {
  9. /// <summary>
  10. /// 判断字符串是否只包含汉字
  11. /// </summary>
  12. /// <param name="input">字符串</param>
  13. /// <returns></returns>
  14. public static bool IsChineseCh(string input)
  15. {
  16. string pattern = @"^[\u4E00-\u9FA5]+$";
  17. Regex regex = new Regex(pattern);
  18. return regex.IsMatch(input);
  19. }
  20. /// <summary>
  21. /// 判断字符串是否只包含英文字母
  22. /// </summary>
  23. /// <param name="input"></param>
  24. /// <returns></returns>
  25. public static bool IsEnglisCh(string input)
  26. {
  27. string pattern = @"^[A-Z]|[a-z]+$";
  28. Regex regex = new Regex(pattern);
  29. return regex.IsMatch(input);
  30. }
  31. /// <summary>
  32. /// 判断字符串是否只包含整数或浮点数
  33. /// </summary>
  34. /// <param name="input">字符串</param>
  35. /// <returns></returns>
  36. public static bool IsNumber(string input)
  37. {
  38. string pattern = @"^-?\d+$|^(-?\d+)(\.\d+)?$";
  39. Regex regex = new Regex(pattern);
  40. return regex.IsMatch(input);
  41. }
  42. /// <summary>
  43. /// 判断字符串是否只包含正整数或正浮点数
  44. /// </summary>
  45. /// <param name="input">字符串</param>
  46. /// <returns></returns>
  47. public static bool IsUNumber(string input)
  48. {
  49. string pattern = @"^([0-9]\d*)(\.\d+)?$";
  50. Regex regex = new Regex(pattern);
  51. return regex.IsMatch(input);
  52. }
  53. /// <summary>
  54. /// 判断字符串是否只包含整数
  55. /// </summary>
  56. /// <param name="input"></param>
  57. /// <returns></returns>
  58. public static bool IsInteger(string input)
  59. {
  60. string pattern = @"^-?\d+$|^(-?\d+)?$";
  61. Regex regex = new Regex(pattern);
  62. return regex.IsMatch(input);
  63. }
  64. /// <summary>
  65. /// 判断字符串是否只包含正整数
  66. /// </summary>
  67. /// <param name="input">字符串</param>
  68. /// <returns></returns>
  69. public static bool IsUInteger(string input)
  70. {
  71. string pattern = @"^\d+$";
  72. Regex regex = new Regex(pattern);
  73. return regex.IsMatch(input);
  74. }
  75. /// <summary>
  76. /// 是否为合法的XML元素节点名称
  77. /// </summary>
  78. /// <param name="pointName">点位名称</param>
  79. /// <returns></returns>
  80. public static bool IsNodeName(string pointName)
  81. {
  82. string RegexStr1 = @"[a-z]|[A-Z]|[_]|[\u4E00-\u9FA5]"; //名称的开头必须是字母、汉字或下划线“_”;
  83. string RegexStr2 = @"^[\w-.]+$"; //名称的字符串只能包含字母,数字,下划线“_”,“-”,“.”;
  84. bool result1 = Regex.IsMatch(pointName.Substring(0, 1), RegexStr1);//判断名称的开头
  85. bool result2 = Regex.IsMatch(pointName, RegexStr2); //判断名称整体
  86. if (result1 && result2) return true;
  87. else return false;
  88. }
  89. }
  90. }