I want to match a pattern like this:
ssfd
or this:
oifdsofijsdf d
So a first name alone or first name and middle initial.
"dsfsf m" =~ /^[A-Za-z]+\s[A-Za-z]$/
To make the middle initial optional, I added the ?:
"dsfsf" =~ /^[A-Za-z](+\s[A-Za-z])?$/
But it gives me error:
target of repeat operator is not specified
What am I doing wrong?
The problem is you misplaced the opening parenthesis and have a "1 or more" operator (+
) right next to it, so the regex doesn't know what you can have one or more of:
^[A-Za-z]+(\s[A-Za-z])?$
Is the regex you likely intended to use (and which seems to work on Rubular for your test cases).
/^[A-Za-z]+\s*[A-Za-z]*$/
*
mean length is 0 or any
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With