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.
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
WorkingWithRegularExpressionsas the activeOmniSharpproject.
Step 2: In Program.cs, delete the existing statements, and then import the following namespace:
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:
Note the following about the code:
The
@character switches off the ability to use ...