C#常用正则验证函数示例

 更新时间:2017年01月23日 11:43:56   作者:pan_junbiao  
这篇文章主要介绍了C#常用正则验证函数,举例分析了C#针对IP验证、价格验证及正整数验证的相关操作技巧,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

本文实例讲述了C#常用正则验证函数。分享给大家供大家参考,具体如下:

1、Ip地址验证

/// <summary>
/// Ip地址验证
/// </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、价格验证

/// <summary>
/// 价格验证
/// </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、正整数验证

/// <summary>
/// 正整数验证
/// </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:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#正则表达式用法总结》、《C#编码操作技巧总结》、《C#中XML文件操作技巧汇总》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结

希望本文所述对大家C#程序设计有所帮助。

相关文章

最新评论

?


http://www.vxiaotou.com