Carlos Laspina
Carlos Laspina

Reputation: 2231

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:

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

I appreciate any help.

Upvotes: 0

Views: 668

Answers (3)

Carlos Laspina
Carlos Laspina

Reputation: 2231

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/

Upvotes: 0

user3344434
user3344434

Reputation:

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);
},

Upvotes: 0

anubhava
anubhava

Reputation: 785316

You can use this regex:

/\b\w+\s+\w+\s*,\s*\w+\s+\w+\b/

Upvotes: 1

Related Questions