On Nov 13, 2008, at 5:49 PM, Shandy Nantz wrote:
> Peter Szinek wrote:
>> Here is a 'full' solution that should cover these cases:
>>
>>>> "Colorado Springs, CO[COS]"[/(\w|\s)+, [A-Z]{2}\[(.+?)\]/,2]
>> => "COS"
>>>> "Denver, CO[DEN]"[/(\w|\s)+, [A-Z]{2}\[(.+?)\]/,2]
>> => "DEN"
>
> I have had to refine my search a little, mostly because getting the  
> last
> four characters turned out not to be a simple thing when using regular
> expressions. I have people entering text via an  
> auto_complete_text_field
> in a rails app; my issues is that on my local machine there parameters
> get passed like this:
>
> Denver, CO[DEN]   or   Colorado Springs, CO[COS]
>
> However, up on the server the parameters get passed like this:
>
> "  Denver, CO[DEN]   "    or   "  Colorado Springs, CO[COS]   "
>
> and for whatever reason (my guess being because regex is a pain in the
> a#%), simply replacing the spaces dident work and cause massive  
> amounts
> of havoic. So I used the code found up above and all was well in the
> world....
>
> Then a new hick-up was encountered:
>
> Toronto, Canada[YYZ]
>
> As you can imagine the regex wouldn't ketch this expression. So I  
> tried
> this:
>
>    params[:airport][:city].gsub(/$\s/, "")
>      [/(\w|\s)+, [A-Z]{2}|[A-Z][a-z]{1,}\[(.+?)\]/,2]
>
> And al' bee it caught the Torono, Canada[YYZ]. Now, however, it  
> fails to
> get the Denver, CO[DEN]. I must have a complete lack of understanding
> when it comes to regex because I always thought that the "|" in the
> above statement meant "or", as in, try and match TWO A-Z OR one A-Z
> FOLLOWED BY one or more a-z. I guess I am drawing a total blank  
> because
> I look at the revised code above and I think it should match all the
> above cases and I cannot figure out for the life of me where it is
> failing. Can someon ehelp, thanks
>
> -S


OK, you're trying to pull the three-letter airport code from within  
the square brackets at the end of the location.

airports = [ "Denver, CO[DEN]",
              "Colorado Springs, CO[COS]",
              "  Denver, CO[DEN]   ",
              "  Colorado Springs, CO[COS]   ",
              "Toronto, Canada[YYZ]",
              "Erlanger, KY[CVG]",
            ]

airports.each do |airport|
   location, code = airport.strip.match(/(.*)\[(.{3})\]/).captures
   puts "#{code} is in '#{location}'"
end

DEN is in 'Denver, CO'
COS is in 'Colorado Springs, CO'
DEN is in 'Denver, CO'
COS is in 'Colorado Springs, CO'
YYZ is in 'Toronto, Canada'
CVG is in 'Erlanger, KY'

Got it?

-Rob


Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com