AlCode AlCode - 3 months ago 23
Ruby Question

Ruby, True/false regex

So I've got an issue where my regex looks like this:

/true|false/
.

When I check the word
falsee
I get a true from this regex, is there a way to just limit it to the exact
true
or
false
words?

Answer

Use this regex:

/^(true|false)$/

It will match the beginning and end of the test string with ^ and $, respectively, so nothing else can be in the string (exact match).

See live example at Regex101.

UPDATE (see @w0lf's comment): The parentheses are to isolate the true|false clause so that they are not grouped incorrectly. (This also puts the true or false match in the first capturing group, but since it seems that you are only matching and not capturing an output, this should not make a difference).


Alternatively, if you simply want to match two values, there are easier ways in Ruby. @SimoneCarletti suggests one. You can also use the basic == or eql? operators. Try running the following script to see that these all work:

values = ["true", "false", "almosttrue", "falsealmost"]
values.each do | value |
  puts value

  # these three are all equivalent
  puts "match with if" if value == "true" || value == "false"
  puts "match with equals?" if (value.eql? "true") || (value.eql? "false")
  puts "match with regex" if /^(true|false)$/.match value

  puts
end
Comments