MMK MMK - 10 days ago 5
ASP.NET (C#) Question

Regular Expression for characters but number and space optional using asp.net web forms

Regular Expression for characters but number and space optional using asp.net web forms.

These are acceptable strings:

Mazhar
mazhar123
mazhar khan1


These are not acceptable:

1233444
@@@@@@
Mazhar@kkk


All Special characters should not be acceptable as well.

Answer

Your question is vague one. There're some issues which are still open:

  1. Do you accept leading spaces e.g. " Mazhar"?
  2. Do you accept trailing spaces e.g. "Mazhar "?
  3. Do you accept double spaces e.g. "Mazhar 123"?
  4. Can a valid string start with digit? e.g. "123 Mazhar"

In case answers are No, No, Yes, No you can put it like this

  // The pattern, you probably are looking for:
  string pattern = @"^[A-Za-z]+([A-Za-z0-9 ]*[A-Za-z0-9])*$";

  string[] tests = new string[] {
    // your test cases (valid strings)
    "Mazhar", "mazhar123", "mazhar khan1",
    // your test cases (invalid strings)
    "1233444", "@@@@@@",  "Mazhar@kkk",
    // my test cases (leading space, trailing space, double space, starts with digit)
    " Mazhar", "Mazhar ", "Mazhar    123", "123Mazhar"
  };

  var report = tests
    .Select(item => Regex.IsMatch(item, pattern)
      ? $"{item,15} is valid"
      : $"{item,15} is NOT valid");

  Console.Write(string.Join(Environment.NewLine, report));

The outcome is

         Mazhar is valid
      mazhar123 is valid
   mazhar khan1 is valid
        1233444 is NOT valid
         @@@@@@ is NOT valid
     Mazhar@kkk is NOT valid
         Mazhar is NOT valid  // leading spaces
        Mazhar  is NOT valid  // trailing spaces
  Mazhar    123 is valid      // we accept double spaces
      123Mazhar is NOT valid  // starts with digit
Comments