Pattern Matching with Regular Expressions
Learn about regular expressions to validate user input, understand their syntax, and efficiently use them for tasks like splitting complex comma-separated strings.
We'll cover the following...
Regular expressions are useful for validating input from the user. They are very powerful and can get very complicated. Almost all programming languages support regular expressions and use a common set of special characters to define them. Let’s try out some example regular expressions:
Step 1: Use your preferred code editor to add a new Console App or console project named WorkingWithRegularExpressions
to the Chapter08
solution or workspace:
In Visual Studio Code, select
WorkingWithRegularExpressions
as the activeOmniSharp
project.
Step 2: In Program.cs
, delete the existing statements, and then import the following namespace:
using System.Text.RegularExpressions; // Regex
Checking for digits entered as text
We will start by implementing the common example of validating number input:
Step 1: 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()!; // null-forgivingRegex ageChecker = new(@"\d");if (ageChecker.IsMatch(input)){WriteLine("Thank you!");}else{WriteLine($"This is not a valid age: {input}");}
Note the following about the code:
The
@
character switches off the ability to use ...