PageRenderTime 38ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/Guanima.Redis/Utils/StringUtils.cs

http://github.com/ccollie/Guanima.Redis
C# | 51 lines | 47 code | 4 blank | 0 comment | 3 complexity | 86a39043b36118bf1a538f9326de59fa MD5 | raw file
  1. using System;
  2. using System.Text.RegularExpressions;
  3. namespace Guanima.Redis.Utils
  4. {
  5. public class StringUtils
  6. {
  7. const string IPRegexPattern = @"
  8. ^( # Anchor to the beginning of the line
  9. # Invalidations
  10. (?!25[6-9]) # If 256, 257...259 are found STOP
  11. (?!2[6-9]\d) # If 260-299 stop
  12. (?![3-9]\d\d) # if 300-999 stop
  13. (?!000) # No zeros
  14. (\d{1,3}) # Between 1-3 numbers
  15. (?:[.-]?) # Match but don't capture a . or -
  16. ){4,6} # IPV4 IPV6
  17. (?<Url>[A-Za-z.\d]*?) # Subdomain is mostly text
  18. (?::)
  19. (?<Port>\d+)";
  20. private static readonly Regex IPRegex = new Regex(IPRegexPattern,
  21. RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
  22. public static bool IsValidIpAddress(string candidate,out string host, out int port)
  23. {
  24. if (!String.IsNullOrEmpty(candidate))
  25. {
  26. Match m = IPRegex.Match(candidate);
  27. if (m.Success)
  28. {
  29. host = m.Groups["Url"].Value;
  30. port = int.Parse(m.Groups["Port"].Value);
  31. return true;
  32. }
  33. }
  34. host = null;
  35. port = 6379;
  36. return false;
  37. }
  38. public static bool IsNumericIpAddress(string candidate)
  39. {
  40. string host = "";
  41. int port = 0;
  42. var good = IsValidIpAddress(candidate, out host, out port)
  43. && String.IsNullOrEmpty(host);
  44. return good;
  45. }
  46. }
  47. }