Reputation: 57
i am stuck at validating user input. i have set of allowed characters "R G B Y" and i am asking for user input. I want to validate if user inputs ONLY characters that are allowed ("R G B Y").
User can input whatever he or she wants as long as input include allowed characters, for example:
user_input1 = "R R R Y"
user_input2 = "Y Y B G"
and so on...
i am totally stuck, i tried with regex:
/[RGBY]/
it is working fine if user inputs allowed characters, but if there will be a mix of allowed and not allowed characters, regex won't catch it :( for example:
wrong_user_input = "Z Z R Y"
i know regex is overkill for this simple task but i cannot think of something else in this moment. any help would be appreciated.... thanks!
Upvotes: 2
Views: 313
Reputation: 110755
Here are some more ways, some of which do not employ a regex.
Negation of: the string contains a character other than "R"
, "G"
, "B"
, "V"
and " "
!('Z Z R Y' =~ /[^RGBY ]/) #=> false
!('R R R Y' =~ /[^RGBY ]/) #=> true
This avoids the need for anchors.
Use String#delete to remove target characters and then see if any characters are left
'Z Z R Y'.delete('RGBY ').empty? #=> false
'R R R Y'.delete('RGBY ').empty? #=> true
One variant of this is to use String#tr:
'Z Z R Y'.tr('RGBY ', '').empty? #=> false
'R R R Y'.tr('RGBY ', '').empty? #=> true
Another is to use String#gsub with a regex:
'Z Z R Y'.gsub(/[RGBY ]/, '').empty? #=> false
'R R R Y'.gsub(/[RGBY ]/, '').empty? #=> true
Convert the string to an array of characters and use a logical comparison
arr = ['R', 'G', 'B', 'Y', ' ']
('Z Z R Y'.chars - arr).empty? #=> false
('R R R Y'.chars - arr).empty? #=> true
Upvotes: 1
Reputation: 54303
There was a related question a while ago, and this came out as the fastest solution :
"Z Z R Y".count("^RGBY ") == 0
#=> false
"R G R Y".count("^RGBY ") == 0
#=> true
It counts characters that are not R,G,B,Y
or space.
Upvotes: 2
Reputation: 369454
Use /^[RGBY ]+$/
as a pattern, so that from the beginning (^) to the end ($) (not partially) whole characters are consisted of allowed characters (R, G, B, Y, or space):
>> "Z Z R Y" =~ /^[RGBY ]+$/
=> nil
>> "R R R Y" =~ /^[RGBY ]+$/
=> 0
Upvotes: 3