You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby CLI程序中使用正则验证五位Zipcode的实现需求

Solution for Validating 5-Digit Zip Codes in Your Ruby CLI

Got it, let's get your zip code validation sorted out for your movie theater scraper CLI. Since you just need to validate the format (not whether the zip code actually exists), a simple regular expression is perfect here—no external gems required.

Step 1: The Right Regular Expression

Use this regex to match exactly 5 digits, with no extra characters before or after:

/\A\d{5}\z/
  • \A anchors the match to the start of the string (avoids leading spaces/characters)
  • \d{5} matches exactly 5 numeric digits
  • \z anchors the match to the end of the string (avoids trailing spaces/characters)
    This is better than checking a numeric range because it preserves leading zeros (like 00001), which are valid for some US zip codes.

Step 2: Update Your program_input Method

Here's the revised code with the validation, plus the lowercase handling for "exit" that you mentioned:

def program_input
  input = gets.chomp.downcase # Handle exit/Exit/EXIT and remove newline
  if input == "exit"
    puts "Enjoy your movie!"
  elsif input.match?(/\A\d{5}\z/) # Validate 5-digit zip code format
    sleep(0.5)
    print "Calculating"
    3.times do
      sleep(0.25)
      print "."
    end
    puts # Add a newline after the dots
    zip_code = input
    scraper = Scraper.new(zip_code)
    # Add logic here to use the scraper (e.g., display theaters/movies)
  else
    # Handle invalid input by prompting the user again
    puts "Oops, that's not a valid input. Please enter a 5-digit zip code or 'exit'."
    program_input # Recursively call the method to get new input
  end
end

Key Improvements:

  • gets.chomp.downcase ensures "exit" is recognized regardless of capitalization, and removes any trailing newline characters.
  • match? is a clean, efficient way to check if the input matches the regex (returns a boolean).
  • Added an else branch to handle invalid inputs (like 4 digits, letters, or random text) and prompt the user again.
  • Replaced the repeated sleep/print with a loop to make the code cleaner.

This will ensure only valid 5-digit zip codes are passed to your scraper, and the program behaves as expected when the user wants to exit.

内容的提问来源于stack exchange,提问作者Levi Borland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:45:24