Regular Expression is a set of characters that can be compared to a string to determine whether a string meets a specified format required.
Let's analyse the Regular expression characters
() Group or subexpression
? Zero of one occurence of previous character or subexpression
Eg : Eg: a? : Zero or one occurence of a
* Zero or more one occurence of previous character or subexpression
Eg : a* : Zero or more occurence of a. That is it can evaluate to no value, a, aa, aaa, etc.
+ One or more occurence of previous character or subexpression
Eg : a+ one ore more occurence of a (shalvin)+ one or more occurence of shalvin
| Either of the character of subexpression.
[123] Matches any one of the enclosing characters.
[a-c] Any character in the specified range
\d Matches a digit
\w Matches any word character
Regular Expressions in .Net Windows Forms
Having seen the basics of Regular Expression let see how to use it for input validation in Windows Forms Application.
using System.Text.RegularExpressions;
private void txtAQues_Validating(object sender, CancelEventArgs e)
{
if (!Regex.IsMatch(txtAQues.Text, "^a?$"))
errorProvider1.SetError(txtAQues, "Only zero or one occurence of a is allowed");
else
errorProvider1.SetError(txtAQues , "");
}
private void txtShalvinQues_Validating(object sender, CancelEventArgs e)
{
if (!Regex.IsMatch(txtShalvinQues.Text, "^(Shalvin)?$"))
errorProvider1.SetError(txtShalvinQues, "Only zero of one occurence of Shalvin is allowed");
else
errorProvider1.SetError(txtShalvinQues , "");
}
Regular Expression Examples
Checking for valid email id.
[A-Z0-9._]+@[A-Z0-9.-+\.[A-Z]{2,4}
Tuesday, February 26, 2008
Regular Expression and .Net Regex.IsMatch()
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment