javascript 用于检查全名的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11522529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regexp for checking the full name
提问by js999
I would like to write a regexp to check if the user inserted at least two words separated by at least one empty space:
我想写一个正则表达式来检查用户是否插入了至少两个由至少一个空格分隔的单词:
Example:
例子:
var regexp = new RegExp(/^[a-z,',-]+(\s)[a-z,',-]+$/i);
regexp.test("D'avid Camp-Bel"); // true
regexp.test("John ---"); // true // but it should be false!
回答by dlras2
Does ^[a-z]([-']?[a-z]+)*( [a-z]([-']?[a-z]+)*)+$
work for you?
^[a-z]([-']?[a-z]+)*( [a-z]([-']?[a-z]+)*)+$
对你有用吗?
[a-z]
ensures that a name always starts with a letter, then [-']?[a-z]+
allows for a seperating character as long as it's followed by at least another letter. *
allows for any number of these parts.
[a-z]
确保名称始终以字母开头,然后[-']?[a-z]+
允许使用分隔字符,只要它后跟至少另一个字母即可。*
允许任意数量的这些部分。
The second half, ( [a-z]([-']?[a-z]+)*)
matches a space followed by another name of the same pattern. +
makes sure at least one additional name is present, but allows for more. ({1,2}
could be used if you want to allow only two or three part names.
后半部分( [a-z]([-']?[a-z]+)*)
匹配一个空格,后跟相同模式的另一个名称。+
确保至少存在一个额外的名称,但允许更多。({1,2}
如果您只想允许两个或三个部分名称,则可以使用。
回答by Henrique Guimar?es Corila?o
This answer also supports unicode characters.
此答案还支持 unicode 字符。
^[\p{L}]([-']?[\p{L}]+)*( [\p{L}]([-']?[\p{L}]+)*)+$
回答by Muhammad Tahseen Ur Rehman
/^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/g
回答by jam_es
Simpler version
更简单的版本
/^([\w]{3,})+\s+([\w\s]{3,})+$/i
([\w]{3,})the first name should contain only letters and of length 3 or more
([\w]{3,})名字应该只包含字母并且长度为 3 或更多
+\sthe first name should be followed by a space
+\s名字后面应该跟一个空格
+([\w\s]{3,})+the second name should contain only letters of length 3 or more and can be followed by other names or not
+([\w\s]{3,})+第二个名字应该只包含长度为 3 或更多的字母,并且后面可以跟其他名字
/iignores the case of the letters. Can be uppercase or lowercase letters
/i忽略字母的大小写。可以是大写或小写字母
回答by Utkanos
A couple of points:
几点:
In JavaScript it's generally better to use literals rather than named constructors (so
/pattern/
rather thannew RegExp()
. (Sure, there are times when you need the constructor route).If you do use the constructor, in the case of RegExp you don't need the delimiting forward slashes
Your current pattern matches only the first word
{1,}
can be written with the modifier+
在 JavaScript 中,通常使用字面量而不是命名构造函数更好(因此
/pattern/
而不是new RegExp()
. (当然,有时您需要构造函数路由)。如果您确实使用构造函数,则在 RegExp 的情况下,您不需要分隔正斜杠
您当前的模式仅匹配第一个单词
{1,}
可以用修饰符写+
Try
尝试
/^([a-z']+(-| )?)+$/i
Note the surname allows for double-barrel surnames.
请注意姓氏允许双桶姓氏。