Validating a given format phone number.
Regular expressions, Validating phone number
Some of the characters with special meaning
. Match any character except newline
\w Match any alphanumeric character
\s Match any whitespace character
\d Match any digit
\b Match the beginning or end of a word
^ Match the beginning of the string
$ Match the end of the string
There are several other ways to specify a repetition
* Repeat any number of times
+ Repeat one or more times
? Repeat zero or one time
{n} Repeat n times
{n,m} Repeat at least n, but no more than m times
{n,} Repeat at least n times
For Example, ^\d{3}-\d{4}$ Validate a seven-digit phone number.
Code Sample
Regex regex = new Regex("^\d{3}-\d{4}$"); // String Pattern
MatchCollection matches = regex.Matches("123-23456"); // Input value to match the given Pattern
MessageBox.Show(matches.Count.ToString()); // If Regular expression matches, then the count will be greater than zero.
// To get all the Satisfied values using Regular expression, we can loop through and we can use them for further use.
foreach (Match nextMatch in matches)
{
MessageBox.Show(nextMatch.ToString());
}