In: Computer Science
C# & ASP.NET
Create a console application that prompts the user to enter a regular expression, and then prompts the user to enter some input and compare the two for a match until the user presses Esc:
The default regular expression checks for at least one
digit.
Enter a regular expression (or press ENTER to use the
default): ^[a- z]+$
Enter some input: apples
apples matches ^[a-z]+$? True
Press ESC to end or any key to try again.
Enter a regular expression (or press ENTER to use the
default): ^[a- z]+$
Enter some input: abc123xyz
abc123xyz matches ^[a-z]+$? False
Press ESC to end or any key to try again.
The Console program is given below. The comments are provided for the better understanding of the logic.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
string inputRegex = "";
string inputString = "";
//Display initial message
Console.WriteLine("The default regular expression checks for at least one digit.");
//Start a continuous loop. The exit condition is taken care inside the loop.
while (true)
{
//Read the regex pattern from the console.
Console.Write("\nEnter a regular expression (or press ENTER to use the default): ");
inputRegex = Console.ReadLine();
//If Enter key is pressed, default the regex pattern to atleast 1 digit.
if (inputRegex == "")
inputRegex = "[0-9]+";
//Read some input
Console.Write("Enter some input: ");
inputString = Console.ReadLine();
//Check if the input matches the regex pattern entered.
bool isMatchFound = Regex.IsMatch(inputString, inputRegex);
//Display the message whether it matches or not.
Console.WriteLine("{0} matches {1} ? {2}", inputString, inputRegex, isMatchFound);
//Read a key from the user.
Console.Write("\nPress ESC to end or any key to try again.");
ConsoleKeyInfo key = Console.ReadKey();
//If the Escape key is pressed, break the loop. Otherwise continue with the loop.
if (key.Key == ConsoleKey.Escape)
break;
}
}
}
The screenshots of the code and output are provided below.