Pattern matching with regular expressions
Regular expressions are useful for validating input from the user. They are very powerful and can get very complicated. Almost all programming languages have support for regular expressions and use a common set of special characters to define them.Let's try out some example regular expressions:
- Use your preferred code editor to add a new Console App /
console
project namedWorkingWithRegularExpressions
to theChapter08
solution. - In
Program.cs
, delete the existing statements and then import the following namespace:
using System.Text.RegularExpressions; // To use Regex.
Checking for digits entered as text
We will start by implementing the common example of validating number input:
- In
Program.cs
, add statements to prompt the user to enter their age and then check that it is valid using a regular expression that looks for a digit character, as shown in the following code:
Write("Enter your age: ");
string input = ReadLine()...