C#中正則表達式的使用實例
/// <summary>
/// 判斷修改數據的格式是否符合要求
/// </summary>
/// <param name="strIsTimLim"></param>
/// <param name="strBeginTime"></param>
/// <param name="strEndTime"></param>
/// <param name="strCalender"></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;
}