-2
image_basename = 'fr-ca-test.png'

Langs = {'ca', 'fr-CA', 'en-CA'}

Langs.each do |locale_code|
  return locale_code /(\b|\_|-)#{locale_code}(\b|\_|-)/i.match(image_basename)

  end
end

When the filename contains fr-CA or en-CA. I would like to returns fr-CA not Ca.

How I can fix my regex?

1
  • Your Langs is invalid. Commented Mar 13, 2019 at 10:40

1 Answer 1

2

I wouldn't use a regexp in this simple example. Using start_with? will very likely be faster and IMHO it is easier to read and to understand:

image_basename = 'fr-ca-test.png'
LANGUAGES = ['fr-CA', 'en-CA', 'ca']

LANGUAGES.find { |code| image_basename.start_with?(code.downcase) }
#=> "fr-CA"
Sign up to request clarification or add additional context in comments.

2 Comments

filename can be 'fr-ca-test.png' or test-'fr-ca.png' or 'blalb-fr-CA-bllb.png'
You might want to use include? instead of start_with? in that case. Furthermore, make sure that your LANGUAGES array is sorted from the most specific to less specific code because find returned the first match.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.