开发者

Regular Expression in exactly this form : Tyler Durden

Hi i need a javascript regex for a name field in my html form. The user should be able to enter multiple names seperated with space. And first character of 开发者_高级运维all names should be a capital. No numbers, special chars. etc.

thank you.


^[A-Z][a-zA-Z]* [A-Z][a-zA-Z]*$

if need more than two names:

^([A-Z][a-zA-Z]*)( [A-Z][a-zA-Z]*)*$


\b([A-Z][a-z]* [A-Z][a-z]*)\b

\b matches a word boundarym with 0 width.


^([A-Z][a-z]* [A-Z][a-z]*)*

will match the following strings and capture them into groups like so:

Tyler Durden something else John Doe another thing Barack Obama

Tyler Durden John Doe Barack Obama


var nameOne = "Tyler Durden";
nameOne.match(/^[A-Z][a-zA-Z]*(\s+[A-Z][a-zA-Z]*)*$/);
>>> [ "Tyler Durden", " Durden" ]

var nameTwo = "Tyler Francis Durden";
nameTwo.match(/^[A-Z][a-zA-Z]*(\s+[A-Z][a-zA-Z]*)*$/);
>>> ["Tyler Francis Durden", " Durden"]

Because of the parenthesis defining a capturing group you get the final name as a captured match. To get the whole name if it matches, use

nameTwo.match(/^[A-Z][a-zA-Z]*(\s+[A-Z][a-zA-Z]*)*$/)[0];
>>> "Tyler Francis Durden"

If you only care about matched vs unmatched, you can just test the return for null


^([A-Z][a-z]* [A-Z][a-z]*)(:b+[A-Z][a-z]* [A-Z][a-z]*)*$

You can use more than one space to separate each name. This is if you interpret being able to give "multiple names" as meaning a single name is a combination of the first and the last name.

This should match multiple names like this:

Bill Smith

or

Bill Smith Brian Jones Allan King

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜