jdog
jdog

Reputation: 10759

ruby regex for a phrase within an address

I am trying to search a string (an address) for a specific street. This is what I but it never returns true? I am trying to find a street that is input as 516 Meils Bella Dr. Boston, MA I thought it might be because the address is coming across with a capital M, but that is NOT the case. What am I doing wrong?

        istrue = false
        if ( self.pickup_address =~ /Meils(.*)/ )
          istrue = true
        end
        if ( self.dropoff_address =~ /Meils(.*)/ )
          istrue = true
        end
        if ( self.pickup_address =~ /^516/ )
          istrue = true
        end
        if ( self.dropoff_address =~ /^516/ )
          istrue = true
        end

Upvotes: 0

Views: 31

Answers (1)

tadman
tadman

Reputation: 211610

Maybe there's something wrong with your data because this does match:

"516 Meils Bella Dr. Boston, MA".match(/Meils(.*)/)
# => #<MatchData "Meils Bella Dr. Boston, MA" 1:" Bella Dr. Boston, MA">

That being said, you can improve this a lot by making a more robust regular expression that captures both conditions:

/\A516|Meils/

There's no need for the (.*) capture unless you're intending to use that, which apparently you don't.

So you can collapse this down to:

[ self.pickup_address, self.dropoff_address ].any? |address|
   addres.match(/\A516|Meils/)
end

Note using \A is better than ^ since it's anchored to the beginning of the string, not the beginning of any line.

Upvotes: 2

Related Questions