user3019354
user3019354

Reputation: 51

String validation with Regex - with a Do while loop

Can I use a do while loop and regex to validate a string input, so that the string is rejected when a number is inside with [:alpha:]

Console.Write("Please Input The student First name/To cancel enter END> ");
StFName[count] = Console.ReadLine();
do
{
      Console.Write("Please Input The student First name/To cancel enter END> ");
      StFName[count] = Console.ReadLine();
} while (StFName =! "[:alpha:]");

This is my Dream scenario

Upvotes: 0

Views: 726

Answers (2)

Matias Cicero
Matias Cicero

Reputation: 26281

do {
   Console.Write("Please Input The student First name/To cancel enter END> ");
   StFName[count] = Console.ReadLine();
} while (Regex.IsMatch(StfName[count], "\\d+"));

Any string with a numeric character will fail the validation.

Alternatively, if you want non-alphanumeric (apart from whitespaces) characters to also fail, you should use the following regex:

do {
   Console.Write("Please Input The student First name/To cancel enter END> ");
   StFName[count] = Console.ReadLine();
} while (!Regex.IsMatch(StfName[count], "[a-zA-Z\\s]+"));

Upvotes: 1

Roman Marusyk
Roman Marusyk

Reputation: 24579

Try to something like:

Console.Write("Please Input The student First name/To cancel enter END> ");
StFName[count] = Console.ReadLine();
do
{
      Console.Write("Please Input The student First name/To cancel enter END> ");
      StFName[count] = Console.ReadLine();
} while (!Regex.IsMatch(StfName[count], "[[:alpha:]]"));

Upvotes: 0

Related Questions