简体   繁体   English

名字和姓氏正则表达式

[英]First and surn name regex

I wrote a Regex to match first / last name for a registration form in my web site.我写了一个正则表达式来匹配我网站上注册表的名字/姓氏。 The requirements are:要求是:

  • Up to 44 chars最多 44 个字符
  • - or ' are acceptable -'是可以接受的
  • One space is acceptable within the names名称中可以有一个空格
  • Unicode is not required不需要 Unicode

Is there any way to make my expression shorter?有什么办法可以让我的表情变短吗?

^[a-zA-Z]{2,12}['-]?[a-zA-Z]{1,10}\s?[a-zA-Z]{2,12}['-]?[a-zA-Z]{1,10}$

Is it too much restrictions for a name field?名称字段是否有太多限制?

First with your regex the response is up to 47 chars : 12+1+10+1+12+1+10.首先使用正则表达式,响应最多为 47 个字符:12+1+10+1+12+1+10。

I think the best way for you is to allow 44 chars from letters, coma, minus or white space.我认为对您来说最好的方法是允许来自字母、逗号、减号或空格的 44 个字符。

You can force the first char to be a letter :您可以强制第一个字符为字母:

^[a-zA-Z][a-zA-Z\-'\s]{0,43}$

Here is what names your code might miss:以下是您的代码可能遗漏的名称:

Jo Blow                  not passed
Hyoung Kyoung Wu         not passed
Mike O'Neal              not passed
d'Are to Beaware         not passed
O Henry Smith            not passed
Mathais d'Arras          not passed
Martin Luther King Jr    not passed
George De FunkMaster     not passed
Kurtis B-Ball Basketball not passed
Ahmad el Jeffe           not passed
An Ni                    not passed

You can try this one that can handle almost all names你可以试试这个可以处理几乎所有名字的

^[^- '](?=(?![A-Z]?[A-Z]))(?=(?![a-z]+[A-Z]))(?=(?!.*[A-Z][A-Z]))(?=(?!.*[- '][- ']))[A-Za-z- ']{2,}$
Jo Blow                      passed
Hyoung Kyoung Wu             passed
Mike O'Neal                  passed
d'Are to Beaware             passed
O Henry Smith                passed
Mathais d'Arras              passed
Martin Luther King Jr        passed
George De FunkMaster         passed
Kurtis B-Ball Basketball     passed
Ahmad el Jeffe               passed
An Ni                        passed

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

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