In: Computer Science
C#
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.
Code:
using System;
using System.Text.RegularExpressions;
namespace regExpressionConsole
{
class Program
{
static ConsoleKeyInfo ckey;
// console key class is used to determine the entered key is esc or not
static void Main(string[] args)
{
String expression;
do
{
Console.WriteLine("Enter a regular expression (or press ENTER to
use the default): ^[a- z]+$");
//Get user input expression if any
string res = Console.ReadLine();
//check whether they entered enter key or not
if(res=="")
{
expression = "^[a-z]+$";
}
else
{
expression = res;
}
//get user input values to compare with the expression
Console.WriteLine("Enter some input ");
string input;
input = Console.ReadLine();
//Matching with the values and expression
var match = Regex.Match(input, expression);
if (match.Success)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
//Confirm whether user ending the application or continuing.
Console.WriteLine("Press Escape to end or any key to try
again..");
ckey = Console.ReadKey();
}
while (ckey.Key != ConsoleKey.Escape);
}
}
}
Output: