C#中正则表达式的使用实例
/// <summary>
/// 判断修改数据的格式是否符合要求
/// </summary>
/// <param></param>
/// <param></param>
/// <param></param>
/// <param></param>
/// <returns></returns>
private bool isPatternValid(string m_strIsTimLim, string m_strBeginTime, string m_strEndTime, string m_strCalender)
{
bool isPatternValid = false;
string patternIsTimLim = @"^[Y|y|N|n]{1}$";//匹配只能输入Y或y或n或N的其中一个
string patternDate = @"^\d{4}[/]([0][1-9]|(1[0-2]))[/]([1-9]|([012]\d)|(3[01]))([ \t\n\x0B\f\r])(([0-1]{1}[0-9]{1})|([2]{1}[0-4]{1}))([:])(([0-5]{1}[0-9]{1}|[6]{1}[0]{1}))([:])((([0-5]{1}[0-9]{1}|[6]{1}[0]{1})))$";//匹配格式如2012/12/15 18:00:00
string patternCalender = @"^\d{4}[-]\d{4}[-]([1|2])$";//匹配年度格式,如:2012-2013-1,这个正则表达式有不完整的地方
//string temp = "2102/12/3 1:22:22";
//Match tempmatch = Regex.Match(temp, patternDate);
//bool tempb =tempmatch.Success;
Match m_patternIsTimLim = Regex.Match(m_strIsTimLim, patternIsTimLim); // 匹配正则表达式,需要添加:using System.Text.RegularExpressions;
Match m_patternBeginDate = Regex.Match(m_strBeginTime, patternDate);
Match m_patternEndDate = Regex.Match(m_strEndTime, patternDate);
Match m_patternCalender = Regex.Match(m_strCalender, patternCalender);
if (m_patternIsTimLim.Success && m_patternBeginDate.Success && m_patternEndDate.Success && m_patternCalender.Success)//序号匹配成功
{
isPatternValid = true;
}
else if (!m_patternIsTimLim.Success)
{//匹配失败
isPatternValid = false;
MessageBox.Show("只能输入Y或y或n或N中的一个字母", "警告", MessageBoxButtons.OKCancel);
}
else if ((!m_patternBeginDate.Success) || (!m_patternEndDate.Success))
{
isPatternValid = false;
MessageBox.Show("时间格式:2012/12/15 18:00:00", "警告", MessageBoxButtons.OKCancel);
}
else if (!m_patternCalender.Success)
{
isPatternValid = false;
MessageBox.Show("如:2012-2013-1或如:2012-2013-2", "警告", MessageBoxButtons.OKCancel);
}
return isPatternValid;
}