Mich Dart
Mich Dart

Reputation: 2422

Ruby regular expressions and substrings

I'm in trouble with these kind of strings:

1) 125******* or 125co****** or 125CO*******
2) 125af***** or 125AF****** or 125f****** or 125AF********

The initial number's length can be between 2 and 11 chars, followed by some substrings (such as "co", "f", etc) and then by alphanumeric strings.

For now I made these two regex, but they don't work properly:

/^([0-9]{2,11})([c]?[o]?)/i
/^([0-9]{2,11})(a?)f/i

Note that both situations should not conflict themselves. 1) and 2) are separate. How can I do?

edit: added from comment:

I've added more informations to explain. Through an admin panel, the user can upload files, and the system should save them into proper directories, based on their names.

Eg. a file called

125.doc or 
125co_tes.doc or 
125CO_tes.doc

should be saved into "collection" directory,
but the ones called

125af.double.jpg or 
125AF-happy.txt or 
125f_testlong.xls or 
125AF.pdf

should be saved into "documents" directory, and so on.

Upvotes: 1

Views: 150

Answers (3)

ohaal
ohaal

Reputation: 5268

Matching files for "collection":

/^(\d{2,11})((?:(?:c?o|co?).*)?\.[a-z0-9]+)$/i

Matching files for "documents":

/^(\d{2,11})((?:af?|a?f).+)$/i

Let me know if it's not strict enough (or too strict) for your application.

Upvotes: 1

Yoann Le Touche
Yoann Le Touche

Reputation: 1300

string="125af.double.jpg"
case string
  when /^([0-9]{2,11})(a?)f/i
    # Document
  when /^([0-9]{2,11})([c]?[o]?)/i
    # Collection
end

If you check /^([0-9]{2,11})(a?)f/i first there's no conflict between the 2 regexps.

Upvotes: 1

Baldrick
Baldrick

Reputation: 24350

With the following, you can test both file types

if filename =~ /^\d{2,11}(co|a?f)?/i 
  if $1 == '' || $1.downcase == 'co'
     # do CO
  elsif $1.downcase == 'af'
     # do AF
  end
end

See in action http://rubular.com/r/7jGxQVJMNC

It will certainly be difficult to maintain if you have more 2 cases...

Upvotes: 0

Related Questions