【这个测试算是在之前的闰年测试的基础上改进的。

通过这个测试,我对正则表达式又有了进一步的了解。】

为了在各网站获取更多的权限,人们需要注册账号,并填写符合要求的密码以及其他信息。

每个网站对密码的要求不同,有的甚至还会判断当前密码的强度(o´ω`o)ノ

我们现在结合正则表达式的语法写一个判断密码是否符合要求的C#程序。

————————————————我是分界线————————————————

 

 

//由于时间关系,特殊字符相关代码尚未实现o(>﹏<)o

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace SoftwareTest_StrongKey
{
public partial class Form1 : Form
{
string key_input = null;

public bool HasBlank(string key)
{
int strLen = key.Length;
//key.Replace(" ", "");
string trim = Regex.Replace(key, @"\s", "");
int strLen2 = trim.Length;
if (strLen != strLen2)
return true;
else
return false;
}
public bool LegalLength(string key)
{
int strLen = key.Length;
if (strLen > 5 && strLen <= 16)
return true;
else
return false;
}
public bool HasNum(string key)
{
//bool findANum = 0;
Regex r = new Regex(@"\d+");
if(r.IsMatch(key))
return true;
else
return false;
}
public bool HasLetter(string key)
{
Regex r = new Regex(@"[a-z]+");
if (r.IsMatch(key))
return true;
else
return false;
}
public bool HasCapLetter(string key)
{
Regex r = new Regex(@"[A-Z]+");
if (r.IsMatch(key))
return true;
else
return false;
}
public bool HasSpecial(string key)
{
Regex r = new Regex(@"[A-Z]+");
if (r.IsMatch(key))
return true;
else
return false;
}

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void textBox_key_TextChanged(object sender, EventArgs e)
{
key_input = this.textBox_key.Text;
}

private void textBox_keyPrompt_TextChanged(object sender, EventArgs e)
{

}

private void textBox_name_TextChanged(object sender, EventArgs e)
{

}

private void button_ok_Click(object sender, EventArgs e)
{
textBox_keyPrompt.Clear();
if (HasBlank(key_input))
{
textBox_keyPrompt.AppendText("请勿输入空白字符:(");
}
else if (!LegalLength(key_input))
{
textBox_keyPrompt.AppendText("密码长度不合要求:(");
}
else if (!HasNum(key_input))
{
textBox_keyPrompt.AppendText("密码须包含数字:(");
}
else if (!HasLetter(key_input))
{
textBox_keyPrompt.AppendText("密码须包含小写字母:(");
}
else if (!HasCapLetter(key_input))
{
textBox_keyPrompt.AppendText("密码须包含大写字母:(");
}
else if (!HasSpecial(key_input))
{
textBox_keyPrompt.AppendText("密码须包含特殊字符:(");
}
else
{
textBox_keyPrompt.AppendText("这是一个很棒的密码:)");
}
}
}
}

————————————————我是分界线————————————————

关键代码一览

HasBlack函数中利用正则匹配空白字符,并用Replace函数去除空白字符;

HasNum函数匹配一个或者多个数字;HasLetter函数匹配一个或者多个小写字母;

HasCapLetter函数匹配一个或者多个大写字母。

【和之前在闰年判断程序中的“^\d+$”相比少了“^”和“$”,即从头到尾不必全为数字。】

————————————————我是分界线————————————————

————————————————我是分界线————————————————

总之,正则表达式还是相当好用的wwww

嘛,程序功能还有一部分未实现,期待下次改进~\(≧▽≦)/~

 

posted on 2015-04-12 23:46  白蜀黍  阅读(816)  评论(0编辑  收藏  举报