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

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. PEB及LDR链

    PEB地址的取得在NT内核系统中fs寄存器指向TEB结构,TEB+0x30处指向PEB结构,PEB+0x0c处指向PEB_LDR_DATA结构,PEB_LDR_DATA+0x1c处存放一些指向动态链接 ...

  2. go时间和日期

    1. time包 2. time.Time类型,用来表示时间 3. 获取当前时间, now := time.Now() 4. time.Now().Day(),time.Now().Minute(), ...

  3. Linux内核同步原语之原子操作【转】

    转自:http://blog.csdn.net/npy_lp/article/details/7262388 避免对同一数据的并发访问(通常由中断.对称多处理器.内核抢占等引起)称为同步. ——题记 ...

  4. 在C#中用MediaInfo获取视频或音频的属性

    MediaInfo是一个开源的获取视频或音频的信息的非常便利的工具,它本身就带有一个GUI界面,可以非常方便我们查看视频信息.但是,当我们写一些转码程序时,往往需要在程序中获取视频信息的时候. 以前我 ...

  5. 2017 ACM - ICPC Asia Ho Chi Minh City Regional Contest

    2017 ACM - ICPC Asia Ho Chi Minh City Regional Contest A - Arranging Wine 题目描述:有\(R\)个红箱和\(W\)个白箱,将这 ...

  6. Tutorial 1: Serialization

    转载自:http://www.django-rest-framework.org/tutorial/1-serialization/#tutorial-1-serialization Tutorial ...

  7. centos 下单独安装mysql

    https://www.cnblogs.com/running-mydream/p/4666094.html https://www.cnblogs.com/lzj0218/p/5724446.htm ...

  8. 如何关闭WordPress后台的主题、插件、版本更新通知?

    由于WordPress 更新速度非常快,不论是主题 插件或是版本,每个月少说要执行个好几次,因为更新快,所以WordPress后台加入了更新通知,提醒使用者有新版本了,可以进行插件.主题或是系统更新, ...

  9. CentOS7.5下时间戳转换为时间

    Unix时间戳(英文为Unix epoch, Unix time, POSIXme 或 Unix timestamp)是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒 一.查 ...

  10. es6的Map()构造函数

    普通的object对象是键值对的集合,但对于它的键却有着严苛的要求,必须是字符串,这给我们平时带来很多的不方便 Map函数类似于对象,但它是一个更加完美的简直对集合,键可以是任意类型 set()方法可 ...