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

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储存过程2:变量定义与参数传递

    #储存过程 中的变量定义 declare 变量名 类型 可选类型 -- 跟建表差不多 create procedure p() begin ); ; select age+number; end$ / ...

  2. 老版本ubuntu更新源地址以及sources.list的配置方法 转

    转自(http://blog.csdn.net/snaking616/article/details/52966634) 1.国内可用的更新源地址: (1)中科大地址 http://mirrors.u ...

  3. koa中间层 文件下载的请求转发

    背景: 前端用a标签发起下载文档的get请求 node中间层接到get请求后将请求转发到java后端 java后端返回文档流传递给node中间层 好处: 后端的java业务逻辑层接口.数据库不向外部暴 ...

  4. 作为一个新手的Oracle(DBA)学习笔记【转】

    一.Oracle的使用 1).启动 *DQL:数据查询语言 *DML:数据操作语言 *DDL:数据定义语言 DCL:数据控制语言 TPL:事务处理语言 CCL:指针控制语言 1.登录 Win+R—cm ...

  5. SPOJ DQUERY D-query (在线主席树/ 离线树状数组)

    版权声明:本文为博主原创文章,未经博主允许不得转载. SPOJ DQUERY 题意: 给出一串数,询问[L,R]区间中有多少个不同的数 . 解法: 关键是查询到某个右端点时,使其左边出现过的数都记录在 ...

  6. 防范SQL注入

    使用占位符的方式写查询语句hibernate

  7. go的匿名组合

    golang也提供了继承机制,但采用组合的文法,因此称为匿名组合.与其他语言不同, golang很清晰地展示出类的内存布局是怎样的. 一  非指针方式的组合 1)基本语法 type base stru ...

  8. Valid Sudoku&&Sudoku Solver

    Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku bo ...

  9. CSU 1412 Line and Circles

    原题链接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1412 题目要求判断是否有一条直线可以穿过所有的圆. 做法:把所有圆心做一次凸包,然后判断 ...

  10. Graves of the Internet - 互联网坟墓

    Graves of the Internet - 互联网坟墓 互联网公司逝去产品列表 以此祭奠那些夕阳下的奔跑,祭奠那些逝去的青春 演示地址 点击 这里 https://myvin.github.io ...