Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, True/false regex

Tags:

regex

ruby

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?

like image 437
AlCode Avatar asked Feb 16 '26 14:02

AlCode


1 Answers

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
like image 176
Jonathan Lam Avatar answered Feb 19 '26 06:02

Jonathan Lam



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!