Home > Net >  Regex to match name prefix
Regex to match name prefix

Time:09-26

I need regex conditions that matches any string satisfying the following condition:

  1. String starts with the prefix Mr., Mrs., Ms., Dr., or Er.

I tried /(?<!prefix )Mr.[a-zA-Z]/ so far, but it didn't work.

CodePudding user response:

(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z]

Explanation:

  • (Mr|Mrs|Ms|Dr|Er) - uses grouping and alternation to match any of the following: Mr, Mrs, Ms, Dr, Er

  • \. - matches the literal . character

  • [a-zA-Z] - matches one or more occurence of an uppercase/lowercase letter.

const regex = /(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z] /;

function validate(str){
  console.log(`${str} matches regex? ${regex.test(str)}`)
}

validate("Mr.John")
validate("Mrs.John")
validate("Ms.John")
validate("Dr.John")
validate("Er.John")
validate("Spectric.Spectric")

CodePudding user response:

To match all variants you can write the pattern as:

^(?:Mrs?|Ms|[DE]r)\.

Regex demo

If there has to be a char A-Za-z following, you could also match optional whitespace chars preceding the character class

^(?:Mrs?|Ms|[DE]r)\.\s*[A-Za-z]

Regex demo

  • Related