CodexBloom - Programming Q&A Platform

Regex scenarios to Match Mixed Case File Extensions in Ruby - Need guide with Case Sensitivity

👀 Views: 45 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
regex ruby case sensitivity Ruby

I'm working on a personal project and I'm working on a personal project and I'm relatively new to this, so bear with me. I'm trying to validate file names using regex in Ruby, but I'm working with issues with matching file extensions that can be in mixed case. For example, I want to match both `file.TXT` and `file.txt`, but my current regex only matches one case. I've tried the following regex: ```ruby regex = /\.(txt|jpg|png)$/ ``` This regex works fine for lower case extensions but fails to capture upper case ones. I've also tried using the `i` flag for case insensitivity: ```ruby regex = /\.(txt|jpg|png)$/i ``` However, this doesn't seem to work as expected either. When I run the following code: ```ruby filenames = ['file.txt', 'file.TXT', 'file.jpg', 'document.PDF'] filenames.each do |name| if name =~ regex puts "Matched: #{name}" else puts "Not matched: #{name}" end end ``` I get the output: ``` Matched: file.txt Matched: file.TXT Matched: file.jpg Not matched: document.PDF ``` It seems to skip any file that doesn't have `txt`, `jpg`, or `png` extensions, and I want it to also match files with `PDF` extension. What am I doing wrong? I need a solution that properly captures any case variation of the specified extensions. Any advice on how to handle this more effectively? Has anyone else encountered this? How would you solve this? I'm coming from a different tech stack and learning Ruby. I appreciate any insights!