简体   繁体   English

正则表达式接受带空格但没有特殊字符的名字和姓氏

[英]Regex to accept first and last name with a space but no special characters

So I'm trying to come up with regex to accept first and last name, but the first and last name is mandatory.所以我试图想出正则表达式来接受名字和姓氏,但名字和姓氏是强制性的。 Special characters are not allowed except - and , and .除了 - 和 , 和 之外,不允许使用特殊字符。 and ' I would also like to make the first and last name min length 2 chars each.和 ' 我还想让名字和姓氏的最小长度分别为 2 个字符。

Some examples.一些例子。 Invalid - firstname无效 - 名字

Invalid - lastname无效 - 姓氏

Invalid - f lastname无效 - f 姓氏

Invalid - firstname l无效 - 名字 l

Valid - firstname lastname有效 - 名字姓氏

Valid - f-name lastname有效 - f-name 姓氏

Valid - fname l'name有效 - fname l'name

I have this regex (.*)([A-Za-z ,.'-]){2} ([A-Za-z ,.'-]){2}(.*) which seems to work for everything except excluding the other special characters like !@ etc. I think the issue is because we must match min length for first and last name, with acceptable characters like in above regex.我有这个正则表达式(.*)([A-Za-z ,.'-]){2} ([A-Za-z ,.'-]){2}(.*)似乎适用于一切除了排除其他特殊字符,如 !@ 等。我认为问题是因为我们必须匹配名字和姓氏的最小长度,以及上面正则表达式中可接受的字符。 But by excluding other special characters, it essentially reverses the logic.但是通过排除其他特殊字符,它本质上颠倒了逻辑。

Here is my regexr这是我的正则表达式

UPDATE for those interested I used two regex matches to get around this issue.对于那些感兴趣的人更新我使用两个正则表达式匹配来解决这个问题。 The second regex is for more than one of the allowed special characters.第二个正则表达式用于多个允许的特殊字符。

var match = nameVal.match(/^[A-Za-z][A-Za-z,.'-]+ +[A-Za-z][A-Za-z,.'-]+$/gm);
var match2 = nameVal.match(/([.,\-']{2})/g);

Thanks @tshiono for you help.感谢@tshiono 的帮助。

Would you please try the following:请您尝试以下操作:

^[A-Za-z,.'-]{2,} +[A-Za-z,.'-]{2,}$

Demo演示

If you want first and last name not to start with special characters, please try instead:如果您希望名字和姓氏以特殊字符开头,请尝试:

^[A-Za-z][A-Za-z,.'-]+ +[A-Za-z][A-Za-z,.'-]+$

[UPDATE] [更新]
As for the forked requirement not to repeat the special character, how about:至于fork要求不要重复特殊字符,怎么样:

^(?:(?:[A-Za-z]|([,.'-]))(?!(?:.*?\1))){2,} +(?:(?:[A-Za-z]|([,.'-]))(?!(?:.*?\2))){2,}$

Demo2演示2

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

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