AlCode
AlCode

Reputation: 565

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?

Upvotes: 2

Views: 387

Answers (4)

Cristian Lupascu
Cristian Lupascu

Reputation: 40566

You need to use the ^ and $ anchors:

/^(true|false)$/

Edit: As Cary pointed out in the comments, the pattern above will also match multiline strings that happen to contain a line with true or false. To avoid this, use the \A and \z delimiters that match the beginning and end of string respectively:

/\A(true|false)\z/

Upvotes: 3

Jonathan Lam
Jonathan Lam

Reputation: 17371

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

Upvotes: 4

Simone Carletti
Simone Carletti

Reputation: 176482

You can use

/^(true|false)$/

or even better

/\A(true|false)\z/

that will match the beginning and end of the string (instead of line). If you only need to match for whose words, it may be more efficient to use a simple array and include?:

%w( true false ).include?(value)

Upvotes: 2

Ursus
Ursus

Reputation: 30071

Try out

/^(true|false)$/

where ^ is the start of a line and $ the end.

Upvotes: 2

Related Questions