[英]How I can do to check if a string contains a comma with a space using a regular expression?
The string contains a name, where the first part corresponds to the name and the second to the lastname. 该字符串包含一个名称,其中第一部分对应于名称,第二部分对应于姓氏。
The regular expression must verify these formats: 正则表达式必须验证以下格式:
"Surname1 Surname2, Name1 Name2"
"Surname1, Name1 Name2 Surname2"
Invalid strings: 无效的字符串:
"Surname1 Surname2 Name1 Name2"
"Surname1, Surname2, Name1 Name2"
"Surname1 Surname2 Name1 Name2,"
I try the following: /([\\w][\\,][\\s]{1}\\b)/
, but did not work 我尝试以下操作:
/([\\w][\\,][\\s]{1}\\b)/
,但是没有用
I appreciate any help. 感谢您的帮助。
您可以使用此正则表达式:
/\b\w+\s+\w+\s*,\s*\w+\s+\w+\b/
If you want to support numbers in the name like your example above. 如果您想使用上面示例中的名称来支持数字。
var validName = function (name) {
return /^\w+ \w+, \w+ \w+$/.test(name);
};
or if any kind of whitespace is allowed between names 或者名称之间是否允许使用任何类型的空格
validName = function (name) {
return /^\w+\s\w+,\s\w+\s\w+$/.test(name);
},
or if you only want to allow US letters 或者如果您只想允许美国字母
validName = function (name) {
return /^[A-Za-z]+ [A-Za-z]+, [A-Za-z]+ [A-Za-z]+$/.test(name);
},
I found a solution that verifies both cases: 我找到了一种验证两种情况的解决方案:
This is the regular expression: /\\b\\w+\\s*\\w*,\\s\\w+\\s\\w+\\s*\\w*\\s*\\w*\\s*\\w*\\s*\\w*$\\b/
这是正则表达式:
/\\b\\w+\\s*\\w*,\\s\\w+\\s\\w+\\s*\\w*\\s*\\w*\\s*\\w*\\s*\\w*$\\b/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.