C#正则表达式的简单应用.
引爆你的博客,程序开发,源代码下载,.net,数据库,Access,SqlServer,Google博客优化,费空间免费域名
这个小例子的源码在http://download.csdn.net/source/1239641
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Text.RegularExpressions;namespace _RegularExpression_{ public partial class RegularExpression : Form { public RegularExpression() { InitializeComponent(); // do initials comboBox1.Items.Add(@"--------------------------------------------------------------------------------------------------------"); comboBox1.Items.Add(@"[\u4e00-\u9fa5]:匹配中文字符"); comboBox1.Items.Add(@"[^\x00-\xff]:匹配双字节字符(包括汉字在内)"); comboBox1.Items.Add(@"^[0-9]*[1-9][0-9]*$:匹配正整数"); comboBox1.Items.Add(@"^((-\d+)|(0+))$:匹配非正整数(负整数 + 0)"); comboBox1.Items.Add(@"^-?\d+$:匹配整数 "); comboBox1.Items.Add(@"--------------------------------------------------------------------------------------------------------"); //comboBox1.Items.Add(@"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$:匹配正浮点数"); comboBox1.Items.Add(@"^\d+(\.\d+)?$:匹配非负浮点数(正浮点数 + 0) "); comboBox1.Items.Add(@"^(-?\d+)(\.\d+)?$:匹配浮点数"); comboBox1.Items.Add(@"^[A-Za-z]+$:匹配英文字母组成的字符串"); comboBox1.Items.Add(@"^[A-Z]+$:匹配英文字母大写字符串"); comboBox1.Items.Add(@"^[a-z]+$:匹配由26个英文字母的小写组成的字符串"); comboBox1.Items.Add(@"--------------------------------------------------------------------------------------------------------"); comboBox1.Items.Add(@"^[A-Za-z0-9]+$:匹配数字和英文字母组成的字符串"); comboBox1.Items.Add(@"^\w+$:匹配由数字、26个英文字母或者下划线组成的字符串 "); comboBox1.Items.Add(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$:匹配email地址"); comboBox1.Items.Add(@"^[a-zA-z]+://匹配(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$:匹配url"); comboBox1.Items.Add(@"^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$:匹配IP"); comboBox1.Items.Add(@"--------------------------------------------------------------------------------------------------------"); //set default selected index this.comboBox1.SelectedIndex = 0; } //验证button被点击的时候 private void btnValidate_Click(object sender, EventArgs e) { //textBox2.Enabled =true; string strTest = comboBox1.Text.ToString().Trim(); string[] strSplit = strTest.Split(':'); //设置正则表达式 Regex r = new Regex(strSplit[0]); //看是否匹配 if (r.IsMatch(textBox2.Text.ToString().Trim())) { textBox3.Clear(); textBox3.Text = "Mathed"; } else { textBox3.Clear(); textBox3.Text = "Not Math!"; //textBox3.Clear(); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.Text == "--------------------------------------------------------------------------------------------------------"|| this.comboBox1.SelectedIndex==-1) { // comboBox1.Text = ""; textBox2.Enabled = false; btnValidate.Enabled = false; } else { textBox2.Enabled = true; btnValidate.Enabled = true; } } }}
0 评论:
发表评论