userFriendly
userFriendly

Reputation: 484

Why is this regular expression failing?

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

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54213

Different stars

You could accept different kind of stars :

/^[\*✭★☆]+$/ =~ '✭✭✭✭✭✭✭✭✭✭✭✭✭✭✭' ? true : false
#=> true

/^[\*✭★☆]+$/ =~ "*✭✭✭★✭★✭☆☆✭★**☆*✭★✭*★★*✭★☆✭☆*★" ? true : false
#=> true

object ? true : false

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.

String#match?

As of Ruby 2.4, you could also use :

'✭✭✭✭✭✭✭✭✭✭✭✭✭✭✭'.match? /^[\*✭★☆]+$/
#=> true

String boundaries

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

Related Questions