Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a boolean value from a regex

I can't quite figure out what I'm doing wrong here..

if @calc.docket_num =~ /DC-000044-10/ || @calc.docket_num =~ /DC-67-09/
  @calc.lda = true
else
  @calc.lda = false
end

But it seems that @calc.docket_num can be any string whatsoever and it always returns as true.

Am I not doing this right?

like image 351
Trip Avatar asked Feb 01 '11 02:02

Trip


People also ask

Does regex return true or false?

JavaScript RegExp test()If it finds a match, it returns true, otherwise it returns false.

Does re search return Boolean?

Does re search return Boolean? Use bool() and re.search() to use regular expressions to return a boolean. Call re.search(pattern, string) to check if pattern occurs anywhere in string . Use bool() to convert the result to a boolean.

Does re match return true?

re. match(...) would return true if the string's beginning part match the regular pattern. While search will confirm the pattern anywhere in the string.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


2 Answers

This is a one-liner:

@calc.lda = !!(@calc.docket_num =~ /DC-000044-10|DC-67-09/)

The !! forces the response to true/false, then you can assign your boolean variable directly.

like image 72
Mark Thomas Avatar answered Oct 02 '22 00:10

Mark Thomas


Alternatively you could use the triple equals (===) operator for the Regexp class which is used for determining equality when using case syntax.

@calc.lda = /DC-000044-10|DC-67-09/ === @calc.docket_num 
@calc.lda
=> true

BEWARE

/Regexp/ === String is totally different than String === /Regexp/!!!! The method is not commutative. Each class implements === differently. For the question above, the regular expression has to be to the left of ===.

For the Regexp implementation, you can see more documentation on this (as of Ruby 2.2.1) here.

like image 42
Curley Avatar answered Oct 01 '22 22:10

Curley