本文参考:http://deerchao.net/tutorials/regex/regex.htm(推荐!)
下面列出几个常见正则表达式并对其分析:
1 匹配只有汉字的字符串:
^[\u4e00-\u9fa5]+$
字符串开始 汉字1或多个 字符串结束
如:汉字
是\,不是/,否则产生异常:
2 匹配手机号:
^1[3-8]\d{9}$
字符串开始 1 3至8中的一个数字 九位数字 字符串结束
如:13123456789
3 匹配Internet URL:
http(s)?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?
http或https :// 字母或数字或下划线或汉字或- 1或多个 . 1或多个 字母或数字或下划线或汉字或- 1或多个 / 字母或数字或下划线或汉字或-或.或0个/或1个/或%或&或= 0或多个 0或1个
如:http://www.abc.com
疑:Visual Studio 2008 asp.net的正则表达式验证控件中给出的Internet URL为http(s)?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?,比上面列出的这个多个空格(在最后一个点前),查资料说URL中不允许出现空格,我不明白微软为什么在此多个空格,望知道的朋友留言。
4 匹配中华人民共和国身份证号:
\d{17}[\d|X]|\d{15}
17位数字 一个数字或字母X 15位数字
如:123456781234567,12345678123456789X
示例代码如下:
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 System.Text.RegularExpressions;
namespace 正则表达式
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (IsChineseCh("字符"))
Console.WriteLine("------输入字符 只包含汉字");
else
Console.WriteLine("------输入字符 不只包含汉字");
if (IsMobilePhone("13123456789"))
Console.WriteLine("------输入字符 是合法手机号");
else
Console.WriteLine("------输入字符 不是合法手机号");
if (IsInternetURL("http://www.abc.com"))
Console.WriteLine("------输入字符 是合法Internet URL");
else
Console.WriteLine("------输入字符 不是合法Internet URL");
}
private bool IsChineseCh(string input)
{
//任何字符可以使用 "/u" 再加上其编号的4位十六进制数表示,
//比如:汉字可以使用“[/u4e00-/u9fa5]”表示
Regex regex = new Regex("^[\u4e00-\u9fa5]+$");
return regex.IsMatch(input);
}
private bool IsMobilePhone(string input)
{
Regex regex = new Regex(@"^1[3-8]\d{9}$");
return regex.IsMatch(input);
}
private bool IsInternetURL(string input)
{
Regex regex = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?");
return regex.IsMatch(input);
}
/// <summary>
/// 匹配中间有0个或1个或2个任意字符(包含换行)的大象,将其替换为|
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMatch_Click(object sender, EventArgs e)
{
textBox2.Clear();
string source = textBox1.Text;
Regex regex = new Regex(@"大(\r\n|.){0,2}象", RegexOptions.IgnoreCase);
string result = regex.Replace(source, "|");
textBox2.Text = result;
}
}
}
vs2008下编译通过,输出结果为:
------输入字符 只包含汉字
------输入字符 是合法手机号
------输入字符 是合法Internet URL