【转】在CS代码中使用正则表达式验证!

代码
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 RegulatorTest
 {
 
public partial class Form1 : Form 
public Form1() 
{ InitializeComponent(); }
 
private void btnTest_Click(object sender, EventArgs e) 
//验证 E-mail 格式
 string regexEmail = "\\w{1,}@\\w{1,}\\.\\w{1,}";
 System.Text.RegularExpressions.RegexOptions options 
= ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline) | System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regEmail = new System.Text.RegularExpressions.Regex(regexEmail, options);
 
string email = txtEmail.Text; 
if (regEmail.IsMatch(email))
//email 填写符合正则表达式 "\\w{1,}@\\w{1,}\\.\\w{1,}" 
{ MessageBox.Show("符合正则表达式:"+regEmail.ToString()+"\n邮箱填写成功!"); }
 
else 
{ MessageBox.Show(
"不符合正则表达式:"+regEmail.ToString()+"\n邮箱格式不正确!");
 
return; } //验证密码 由不小于6位不大于15位的字母数字下划线特殊符号组成! string regexPwd = "^.{6,15}___FCKpd___0quot;;//限定开头,须从第一位开始匹配,限定结尾,总位数不得超过15位,否则即使大于15位仍然可以验证通过 System.Text.RegularExpressions.Regex regPwd = new System.Text.RegularExpressions.Regex(regexPwd, options); string pwd = txtPwd.Text; if (regPwd.IsMatch(pwd)) { MessageBox.Show("符合正则表达式:"+regPwd.ToString()+"\n密码验证通过!"); } else { MessageBox.Show("不符合正则表达式:"+regPwd.ToString()+"\n密码验证失败!密码应由不小于6位不大于15位的字母数字下划线特殊符号组成!"); return; } } private void Form1_Load(object sender, EventArgs e) { } } } 
原文地址:https://www.cnblogs.com/gebenhagen/p/1629161.html