Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

target of repeat operator is not specified when using optional character

Tags:

regex

ruby

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?

like image 364
Daniel Viglione Avatar asked Oct 20 '25 04:10

Daniel Viglione


2 Answers

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).

like image 64
Simple Lime Avatar answered Oct 21 '25 19:10

Simple Lime


/^[A-Za-z]+\s*[A-Za-z]*$/

* mean length is 0 or any

like image 31
tsogtgerel.ts Avatar answered Oct 21 '25 19:10

tsogtgerel.ts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!