简体   繁体   English

如何使用正则表达式检查字符串是否包含逗号和空格?

[英]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.

相关问题 如何使用正则表达式检查行包含内联sql语句? - How can I check line contains inline sql statement using Regular Expression? 使用正则表达式如何查找字符串是否以正确的序列顺序包含特定序列的所有字符? - Using a Regular Expression how can i find if a string contains all the characters of a specific sequence in the correct sequence order? 如何使用正则表达式检查输入是否为数字? - how do I check if input is a number using regular expression? 如何使用正则表达式检查单词是否带有括号 - How can I check if a word has parentheses using regular expression 如何使用JavaScript正则表达式检查字符串是否包含至少一个字母? - How to check whether a String contains at least one letter using JavaScript Regular Expression? 如何使用 Ajv 的正则表达式验证字符串? - How do I validate a string using a regular expression with Ajv? 如何检查正则表达式中输入的只有数字和空格? - how can I check the input is only number and white space in regular expression? 如何使用正则表达式替换/拆分动态字符串? - How can I replace/split a dynamic string using regular expression? 如何在javascript中检查字符串是否只包含数字,逗号和带正则表达式的句点? - How can I check if a string contains only numbers, comma and periods with regex in javascript? 逗号和空格分隔的数字和连字符分隔的字符串正则表达式 - comma and space separated number and hyphen separated string regular expression
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM