Examples of C Common Regular Validation Functions

  • 2021-11-29 08:11:47
  • OfStack

In this paper, examples are given to describe the regular verification functions commonly used in C #. Share it for your reference, as follows:

1. Ip Address Verification


/// <summary>
/// Ip Address authentication 
/// </summary>
public static bool CheckIp(string ip)
{
  bool result = false;
  Regex ipReg = new Regex(@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
  if (ipReg.IsMatch(ip))
  {
    result = true;
  }
  return result;
}

2. Price verification


/// <summary>
///  Price verification 
/// </summary>
/// <param name="priceStr"></param>
/// <returns></returns>
public bool CheckPrice(string priceStr)
{
  bool result = false;
  Regex regex = new Regex(@"^\d+(\.\d{1,2})?$", RegexOptions.IgnoreCase);
  Match match = regex.Match(priceStr);
  if (match.Success)
  {
    result = true;
  }
  return result;
}

3. Positive integer verification


/// <summary>
///  Positive integer validation 
/// </summary>
public static bool CheckPositiveInteger(string numStr)
{
  bool result = false;
  Regex regex = new Regex(@"^[1-9]\d*$", RegexOptions.IgnoreCase);
  Match match = regex.Match(numStr);
  if (match.Success)
  {
    result = true;
  }
  return result;
}

PS: Here are two very convenient regular expression tools for your reference:

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg

For more readers interested in C # related content, please check the topics on this site: "Summary of C # Regular Expression Usage", "Summary of C # Coding Operation Skills", "Summary of XML File Operation Skills in C #", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "Summary of Thread Use Skills in C # Programming"

I hope this article is helpful to everyone's C # programming.


Related articles: