juan perez
juan perez

Reputation: 323

Regular Expression in Ruby on Rails

I need create a regular expression for validate the first and second name of a person. The second name is optional because there are people without second name. The space character can be between the two names, but it can not be the end of string

example

 "Juan Perez" is valid
 "Juan Perez " is invalid because there is a space character the end of the string

Upvotes: 0

Views: 117

Answers (2)

pguardiario
pguardiario

Reputation: 54984

How about a way that doesn't require repeating the char class:

^\b(\s?[[:alpha:]]+)+$

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

You could use the below regex which uses an optional group.

^[A-Za-z]+(?:\s[A-Za-z]+)?$

(?:\s[A-Za-z]+)? optional group will do a match if there is a space followed by one or more alphabets. It won't match the string if there is only a single space exists. And also it asserts that there must be an alphabet present at the last.

DEMO

Update:

If the user name contains not only the firstname but also middlename,lastname ... then you could use the below regex. * repeats the previous token zero or more times where ? after a token (not of * or +) will turn the previous token as an optional one.

^[A-Za-z]+(?:\s[A-Za-z]+)*$

Upvotes: 2

Related Questions