简体   繁体   English

Javascript 正则表达式匹配名称和标题

[英]Javascript regex match for name with title

I was trying to create JavaScript regex for name with title like Mr. John Son.我试图创建 JavaScript 正则表达式,其名称为 John Son 先生。 The name can have many titles like Mr. Miss. Mrs. Dr. Er.这个名字可以有很多头衔,比如Mr. Miss. Mrs. Er. 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.正则表达式的错误在于,如果标题出现两次像 Mr.Mr. 一样,它会返回 true。 John Son约翰逊

I have specified the quantifier {1} after the title.我在标题后指定了量词 {1}。 But it still returns true, if the title appears twice before the name.但如果标题在名称之前出现两次,它仍然返回 true。 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.您可以使用以下链接在线测试您的正则表达式 regex101.com 并清楚地了解您的正则表达式如何匹配。

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您可以尝试的示例仅在称呼恰好出现一次时才与名称匹配/(\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 .上面的正则表达式仅将单词和空格视为称呼之后的有效字符,因此 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.可能有其他方法可以达到相同的结果,所以最好阅读正则表达式(这里是一个备忘单)并尝试不同的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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