Search code examples
c#asp.netregexregular-language

Regular Expression to match Salutation


I used the following regular expression:

[RegularExpression(@"^(Mr. .*|MR. .*|MRS. .*|Mrs. .*|MS. .*|Ms. .*|DR. .*|Dr. .*)", ErrorMessage = "Greeting must begin with Mr., Mrs., Ms., or Dr. and be followed by a name.")]
 public string? Greeting { get; set; }

How can I force user to enter space after Mr., MR., MRs., Mrs., then at least one character after the space.

For example: if they enter Mr. Joe Doe or Mr. Joe is valid but they enter Mr. with space only or Mr. without space is invalid.


Solution

  • Couple of issues

    . matches "any character" so saying Mr. allows someone to write Mra Mrb etc - put a \ before it or put it in a character class (surround it with [ ])

    * means "zero or more of" so a regex of Mr. .* allows them to write zero characters for the name. To quantify "one or more" we use + instead of *

    If you want to do away with repetitive elements you could

    (M[rRsS]|M(RS|rs)|D[rR])\. \w+
    

    The first one takes care of Mr and Ms, second takes care of Mrs, third Dr, then is the common element of "literally a period" followed by a succession of word characters