-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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Bolo
  • 2,668
  • 4
  • 27
  • 34

1 Answers1

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"
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • filename can be 'fr-ca-test.png' or test-'fr-ca.png' or 'blalb-fr-CA-bllb.png' – Bolo Mar 13 '19 at 13:37
  • 1
    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. – spickermann Mar 13 '19 at 13:41