输入的字符串校验,是开发中经常遇到的问题,常用的办法是利用正则表达式进行判断。其特点是简洁有效。

1、正则表达基础知识

  正则表达式的教程很多,这里两个基础教程:

  a、http://www.cnblogs.com/youring2/archive/2009/11/07/1597786.html

  b、http://wenku.baidu.com/view/b473c4de50e2524de5187e74.html

2、常用的正则表达式

下面是一些常用的基于正则表达式的字符串校验

 "^\d+$" //非负整数(正整数 + 0)
"^[0-9]*[1-9][0-9]*$" //正整数
"^((-\d+)|(0+))$" //非正整数(负整数 + 0)
"^-[0-9]*[1-9][0-9]*$" //负整数
"^-?\d+$" //整数
"^\d+(\.\d+)?$" //非负浮点数(正浮点数 + 0)
"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮点数
"^((-\d+(\.\d+)?)|(0+(\.0+)?))$" //非正浮点数(负浮点数 + 0)
"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //负浮点数
"^(-?\d+)(\.\d+)?$" //浮点数
"^[A-Za-z]+$" //由26个英文字母组成的字符串
"^[A-Z]+$" //由26个英文字母的大写组成的字符串
"^[a-z]+$" //由26个英文字母的小写组成的字符串
"^[A-Za-z0-9]+$" //由数字和26个英文字母组成的字符串
"^\w+$" //由数字、26个英文字母或者下划线组成的字符串
"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$" //email地址
"^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$" //url
/^(d{}|d{})-((([-]{}))|([|]))-(([-]([-]{}))|([|]))$/ // 年-月-日
/^((([-]{}))|([|]))/(([-]([-]{}))|([|]))/(d{}|d{})$/ // 月/日/年
"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$" //Emil
"(d+-)?(d{4}-?d{7}|d{3}-?d{8}|^d{7,8})(-d+)?" //电话号码
"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$" //IP地址

参考来源:http://blog.csdn.net/microlchen/article/details/7445846

3、示例

现在通过整理一些资料编写了一个正则表达式验证的类库,供以后需要使用。

a、验证类库,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Text.RegularExpressions; namespace cxlib
{
/// <summary>
/// Regexlib 的摘要说明。
/// </summary>
public class CxRegexLib
{
public CxRegexLib()
{
//
// TODO: 在此处添加构造函数逻辑
//
} //验证Email地址
public bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, "^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$");
} //dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。
public string MDYToDMY(String input)
{
return Regex.Replace(input,"//b(?//d{1,2})/(?//d{1,2})/(?//d{2,4})//b","${day}-${month}-${year}");
} //验证是否为小数
public bool IsValidDecimal(string strIn)
{
return Regex.IsMatch(strIn,"^[0]{0,1}[.]{1}[0-9]{1,}$");
}
//验证两位小数
public bool Is2Decimal(string str_decimal)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_decimal, @"^[0-9]*[.]{1}[0-9]{2}$");
}
//验证一年的12个月
public bool IsMonth(string str_Month)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_Month, @"^(0?[[1-9]|1[0-2])$");
} //验证一个月的31天
public bool IsDay(string str_day)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_day, @"^((0?[1-9])|((1|2)[0-9])|30|31)$");
} //验证是否为电话号码
public bool IsValidTel(string strIn)
{
return Regex.IsMatch(strIn,@"(/d+-)?(/d{4}-?/d{7}|/d{3}-?/d{8}|^/d{7,8})(-/d+)?");
} //验证年月日
public bool IsValidDate(string strIn)
{
return Regex.IsMatch(strIn,@"^2/d{3}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[1-2]/d|3[0-1])(?:0?[1-9]|1/d|2[0-3]):(?:0?[1-9]|[1-5]/d):(?:0?[1-9]|[1-5]/d)$");
} //验证后缀名
public bool IsValidPostfix(string strIn)
{
return Regex.IsMatch(strIn,@"/.(?i:gif|jpg)$");
} //验证字符是否在4至12之间
public bool IsValidByte(string strIn)
{
return Regex.IsMatch(strIn,@"^[a-z]{4,12}$");
} //验证IP
public bool IsValidIp(string strIn)
{
return Regex.IsMatch(strIn,@"^(/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])$");
}
// 验证输入汉字
public bool IsChinese(string str_chinese)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_chinese, @"^[/u4e00-/u9fa5],{0,}$");
} //验证输入字符串 (至少8个字符)
public bool IsLength(string str_Length)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_Length, "^.{8,}$");
} //验证数字输入
public bool IsNumber(string str_number)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_number, "^[0-9]+$");
} //验证整数
public bool IsInteger(string str_number)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_number, "^[-,+]?[0-9]+$");
} //验证手机
public bool IsCellphoneNum(string str_number)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_number, "^[1]{1}[0-9]{10}$");
}
// 验证密码长度 (6-18位)
public bool IsPasswLength(string str_Length)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_Length, "^/d{6,18}$");
} }
}

b、调用代码,如下所示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using cxlib; namespace TestInputValidation
{
public partial class Form1 : Form
{
CxRegexLib cxregex;
public Form1()
{
InitializeComponent();
cxregex = new CxRegexLib();
} private void textBox1_Leave(object sender, EventArgs e)
{
bool flag = cxregex.IsValidEmail(textBox1.Text.Trim());
if (flag == false)
{
toolStripStatusLabelResult.Text = "邮箱格式不正确!";
}else
{
toolStripStatusLabelResult.Text = "邮箱格式正确!";
}
} private void textBox2_Leave(object sender, EventArgs e)
{
bool flag = cxregex.IsValidDecimal(textBox2.Text.Trim());
if (flag == false)
{
toolStripStatusLabelResult.Text = "不是小数!";
}
else
{
toolStripStatusLabelResult.Text = "这是小数!";
}
} private void textBox3_Leave(object sender, EventArgs e)
{
bool flag = cxregex.Is2Decimal(textBox3.Text.Trim());
if (flag == false)
{
toolStripStatusLabelResult.Text = "不是保留两位小数!";
}
else
{
toolStripStatusLabelResult.Text = "保留两位小数!";
}
} private void textBox4_Leave(object sender, EventArgs e)
{
bool flag = cxregex.IsNumber(textBox4.Text.Trim());
if (flag == false)
{
toolStripStatusLabelResult.Text = "不是数字!";
}
else
{
toolStripStatusLabelResult.Text = "这是数字!";
}
}

private void textBox5_Leave(object sender, EventArgs e)
{
bool flag = cxregex.IsInteger(textBox5.Text.Trim());
if (flag == false)
{
toolStripStatusLabelResult.Text = "不是整数!";
}
else
{
toolStripStatusLabelResult.Text = "这是整数!";
}
} private void textBox6_Leave(object sender, EventArgs e)
{
bool flag = cxregex.IsCellphoneNum(textBox6.Text.Trim());
if (flag == false)
{
toolStripStatusLabelResult.Text = "不是手机!";
}
else
{
toolStripStatusLabelResult.Text = "这是手机!";
}
}
}
}

c、运行程序,界面如下图所示:

  通过Tab键,离开编辑框后进行正确性校验。

d、代码工程:

  TestInputValidation.zip

C# 基于正则表达式的字符串验证的更多相关文章

  1. MFC中用正则表达式进行有效性验证

    转载自:http://blog.csdn.net/jinhill/article/details/5928993 正则表达式最实用的一个地方是验证用户输入.它可以轻松验证邮编.电话号码.信用卡号码-- ...

  2. 基于Token的身份验证——JWT

    初次了解JWT,很基础,高手勿喷. 基于Token的身份验证用来替代传统的cookie+session身份验证方法中的session. JWT是啥? JWT就是一个字符串,经过加密处理与校验处理的字符 ...

  3. Notepad++快捷键&正则表达式替换字符串&插件

    Notepad++绝对是windows下进行程序编辑的神器之一,要更快速的使用以媲美VIM,必须灵活掌握它的快捷键,下面对notepad++默认的快捷键做个整理(其中有颜色的为常用招数): 1. 文件 ...

  4. 如何使用JavaScript和正则表达式进行数据验证

    利用客户端JavaScript的优势,JavaScript中的正则表达式可以简化数据验证的工作,下面与大家分享下如何使用JavaScript和正则表达式进行数据验证,感兴趣的朋友可以参考下哈 数据验证 ...

  5. js 常用正则表达式表单验证代码

    正则表达式使用详解 简介 简单的说,正则表达式是一种可以用于模式匹配和替换的强有力的工具.其作用如下:测试字符串的某个模式.例如,可以对一个输入字符串进行测试,看在该字符串是否存在一个电话号码模式或一 ...

  6. JavaScript基础知识(正则表达式、字符串)

    23.正则表达式 作用:定义一个特定的验证字符串内容规则的表达式 注:正则表达式并不是JavaScript独有的:JavaScript支持正则表达式 var a = { };  // 定义一个空对象  ...

  7. js常用正则表达式表单验证代码

    方法一:  var re=/正则表达式/;  re.test($("txtid").val())  方法二:  $("txtid").val.match(/正则 ...

  8. 基于Token的身份验证--JWT

    初次了解JWT,很基础,高手勿喷. 基于Token的身份验证用来替代传统的cookie+session身份验证方法中的session. JWT是啥? JWT就是一个字符串,经过加密处理与校验处理的字符 ...

  9. C#中常用的字符串验证

    using System; using System.Text.RegularExpressions; namespace Util { public static class @string { # ...

随机推荐

  1. mysql中列的增删改

    增加列: ); ) after id; ) first; 修改列名: ); #change可改名字与字段类型 mysql> alter table a change uid uid int; Q ...

  2. Linux运维常用的几个命令介绍【转】

    Linux运维常用的几个命令介绍 1. 查看系统内核版本​ [root@funsion geekxa]# cat /etc/issue CentOS release 6.5 (Final) Kerne ...

  3. 20行js代码制作网页刮刮乐

    分享一段用canvas和JS制作刮刮乐的代码,JS部分去掉注释不到20行代码效果如下 盖伦.jpg 刮刮乐.gif HTML部分 <body> ![](img/gailun.jpg) &l ...

  4. redis源码分析——aofrewrite

    随着redis的运行,aof会不断膨胀(对于一个key会有多条aof日志),导致通过aof恢复数据时,耗费大量不必要的时间.redis提供的解决方案是aof rewrite.根据db的内容,对于每个k ...

  5. Builder设计模式--改善构造器多个参数时可显著改善可读性

    作为一名程序开发者,设计模式其实一直有在接触,只是没有专门的去学过,所以可能对设计模式没有一个系统的理解.在一次项目中,需要使用到第三方服务商提供的功能,为了尽快的熟悉其功能代码,在官网下了demo来 ...

  6. shell之read命令

    一.概述 read命令接收标准输入(键盘)的输入,或者其他文件描述符的输入.得到输入后,read命令将数据放入一个标准变量中. 二.使用举例(这里仅列出一些常用的选项) 1.基本读取 #!/bin/b ...

  7. mac os版本Intellij IDEA 搭建spring mvc的maven工程(新手教学)

    由于近期换了新公司,又换mac pro作为新电脑,打算把用了很多年的eclipse换成IDEA(IDEA比eclipse的好处我就不多说了),由于mac os和IDEA刚开始用不久,所以专门用一篇博客 ...

  8. 20165301 2017-2018-2 《Java程序设计》第九周学习总结

    20165301 2017-2018-2 <Java程序设计>第九周学习总结 教材学习内容总结 第十三章:Java网络编程 URL类 通常包含三部分信息:协议.地址.资源 协议必须是URL ...

  9. cocos2dx 开发配置的一些环境变量(mac/linux)

    通常开发需要配置一些环境变量,下面把我电脑的部分配置分析一下. 1.android开发配置,ndk,sdk,ant 2.cocos2dx开发配置,cocos2d-x export COCOS2DX_R ...

  10. iOS控制器与视图加载方法

    转载记录, 请看原文: 1. iOS中的各种加载方法(initWithNibName,loadNibNamed,initWithCoder,awakeFromNib等等)简单使用   http://w ...