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:
- Create a new console application project named
WorkingWithRegularExpressions
, add it to the workspace, and select it as the active project for OmniSharp. - At the top of the file, import the following namespace:
using System.Text.RegularExpressions;
Checking for digits entered as text
Let's implement the common example of validating number input:
- In the
Main
method, 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(); var ageChecker = new Regex...