Extract file extension

From Rosetta Code
Extract file extension is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program that takes one string argument representing the path to a file and returns the files extension, or the null string if the file path has no extension. An extension appears after the last period in the file name and consists of one or more letters or numbers.

Show here the action of your routine on the following examples:

  1. picture.jpg returns .jpg
  2. http://mywebsite.com/picture/image.png returns .png
  3. myuniquefile.longextension returns .longextension
  4. IAmAFileWithoutExtension returns an empty string ""
  5. /path/to.my/file returns an empty string as the period is in the directory name rather than the file
  6. file.odd_one returns an empty string as an extension (by this definition), cannot contain an underscore.


C#

<lang C#> public static string ExtractExtension(string str) {

           string s = str;
           string temp = "";
           string result = "";
           bool isDotFound = false;
           for (int i = s.Length -1; i >= 0; i--)
           {
               if(s[i].Equals('.'))
               {
                   temp += s[i];
                   isDotFound = true;
                   break;
               }
               else
               {
                   temp += s[i];
               }
           }
           if(!isDotFound)
           {
               result = "";
           }
           else
           {
               for (int j = temp.Length - 1; j >= 0; j--)
               {
                   result += temp[j];
               }
           }
           return result;

} </lang>

J

Implementation:

<lang J>require'regex' ext=: '[.][a-zA-Z0-9]+$'&rxmatch ;@rxfrom ]</lang>

Obviously most of the work here is done by the regex implementation (pcre, if that matters - and this particular kind of extpression tends to be a bit more concise expressed in perl than in J...).

Perhaps of interest is that this is an example of a J fork - here we have three verbs separated by spaces. Unlike a unix system fork (which spins up child process which is an almost exact clone of the currently running process), a J fork is three independently defined verbs. The two verbs on the edge get the fork's argument and the verb in the middle combines those two results.

The left verb uses rxmatch to find the beginning position of the match and its length. The right verb is the identity function. The middle verb extracts the desired characters from the original argument. (For a non-match, the length of the "match" is zero so the empty string is extracted.)

Task examples:

<lang J> ext 'picture.jpg' .jpg

  ext 'http://mywebsite.com/picture/image.png'

.png

  ext 'myuniquefile.longextension'

.longextension

  ext 'IAmAFileWithoutExtension'
  ext '/path/to.my/file'
  ext 'file.odd_one'

</lang>