Reputation: 33
I need regex conditions that matches any string satisfying the following condition:
I tried /(?<!prefix )Mr.[a-zA-Z]/
so far, but it didn't work.
Upvotes: 3
Views: 2507
Reputation: 163577
To match all variants you can write the pattern as:
^(?:Mrs?|Ms|[DE]r)\.
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]
Upvotes: 0
Reputation: 31992
(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")
Upvotes: 3