简体   繁体   中英

Javascript regex match for name with title

I was trying to create JavaScript regex for name with title like Mr. John Son. The name can have many titles like Mr. Miss. Mrs. Dr. Er. etc. I have written a regex

var re = /(\b(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.){1}[a-zA-Z])/i; to get valid names. The error in regex is that it returns true if the title appears twice like Mr.Mr. John Son

I have specified the quantifier {1} after the title. But it still returns true, if the title appears twice before the name. Can you tell what is the error in this regex?

There is nothing wrong with the regex provided per say. The given string is being matched by the regex due to the presence of Mr. The second salutation doesn't matter and is ignored by the regex since the first salutation matches the regex.

You can use the following link to test your regex online regex101.com and get a clear picture of how your regex does matching.

In case you want the matching to fail if salutation occurs more than once then you will need to try something else. An example of something you could try out that will match with a name only if the salutation is present exactly once /(\b(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.){1}^[\w\s]*$)/i

The above regex considers only words and spaces as valid characters after the salutation so a present of a . which is typical in salutation breaks the regex. There are likely other ways of achieving the same result so best is to read up on regex (here is a cheatsheet ) and try different solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM