Reputation: 484
I'm trying to match a string to regexp, but it is returning false when I believe it should be returning true.
/^★+$/ =~ '✭✭✭✭✭✭✭✭✭✭✭✭✭✭✭' ? true : false
#irb example:
2.2.2 :001 > /^★+$/ =~ '✭' ? true : false
=> false
Upvotes: 0
Views: 162
Reputation: 54213
You could accept different kind of stars :
/^[\*✭★☆]+$/ =~ '✭✭✭✭✭✭✭✭✭✭✭✭✭✭✭' ? true : false
#=> true
/^[\*✭★☆]+$/ =~ "*✭✭✭★✭★✭☆☆✭★**☆*✭★✭*★★*✭★☆✭☆*★" ? true : false
#=> true
Note that a ternary operator which returns true
or false
is probably useless, because it converts truthy to true
and falsey to false
.
You could just use :
/^[\*✭★☆]+$/ =~ '✭✭✭✭✭✭✭✭✭✭✭✭✭✭✭'
#=> 0
Since 0
is truthy, it wouldn't change anything for boolean logic.
As of Ruby 2.4, you could also use :
'✭✭✭✭✭✭✭✭✭✭✭✭✭✭✭'.match? /^[\*✭★☆]+$/
#=> true
Finally, if you want to check that the whole string is full of stars, you shouldn't use ^
or $
but \A
and \z
:
p "✭✭✭✭✭✭✭✭✭\nI'm not a star!!!\n✭✭✭✭✭✭".match? /^[\*✭★☆]+$/
#=> true
p "✭✭✭✭✭✭✭✭✭\nI'm not a star!!!\n✭✭✭✭✭✭".match? /\A[\*✭★☆]+\z/
#=> false
Upvotes: 5