16
\$\begingroup\$

Your challenge is to find the file extension of a provided filename:

hi.txt -> txt or .txt
carrot.meme -> meme or .meme
lol (undefined behavior)
what..is..this..file -> file or .file
.bashrc -> bashrc or .bashrc
T00M@n3KaPZ.h0wC[]h -> h0wC[]h or .h0wC[]h
agent.000 -> 000 or .000

You must get the text from the last . or after the last . to the end of the string. The first capturing group match of the regular expression /\.([^.]+)$/ works, and so does splitting the input on .s and returning the last one.

The file name will always contain at least one ., but it may contain multiple .. (see examples)

The input will always match ^[.a-zA-Z0-9^!\[\]{}@$%+=]+$.

\$\endgroup\$
  • 18
    \$\begingroup\$ Please consider using the Sandbox in the future to get feedback on your challenges before posting them to the main site. \$\endgroup\$ – user45941 May 16 '17 at 20:45
  • 1
    \$\begingroup\$ codegolf.meta.stackexchange.com/a/12432/59376 - Got this idea from your challenge. \$\endgroup\$ – Magic Octopus Urn May 16 '17 at 21:51
  • \$\begingroup\$ @carusocomputing nice challenge! \$\endgroup\$ – programmer5000 May 17 '17 at 0:06
  • 2
    \$\begingroup\$ why the negative votes? Is this challenge "exceedingly trivial" or so ? \$\endgroup\$ – Abel Tom May 17 '17 at 5:09
  • \$\begingroup\$ @AbelTom edit history would suggest downvotes were for the lack of specifications in the first draft of this question. \$\endgroup\$ – Patrick Roberts May 17 '17 at 5:12

92 Answers 92

2
\$\begingroup\$

Octave, 24 bytes

@(x)strsplit(x,'.'){end}

Creates an anonymous function named ans which can accept a string as input

Online Demo

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Pyth, 5 bytes

ecz\.

try it here

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 6 4 bytes

-2 bytes thanks to Erik the Outgolfer

⊟⪪S.

Try it online!

Explanation

⊟      Pop
  ⪪ .  Split on "."
   S  Next input as string
       Implicit print of value
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Can't you use ⊟x instead of §x±¹? \$\endgroup\$ – Erik the Outgolfer May 17 '17 at 13:13
2
\$\begingroup\$

REXX 53

parse value reverse(arg(1)) with e "." 
say reverse(e)
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

C#, 35 bytes

s=>s.Substring(s.LastIndexOf("."));

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Haskell, 32 30 29 bytes

-1 byte thanks to Laikoni

r=reverse
r.fst.span(/='.').r

self-explanatory

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ takeWhile can be shortened to fst.span. \$\endgroup\$ – Laikoni May 17 '17 at 16:17
2
\$\begingroup\$

Cheddar, 16 bytes

@.sub(/.*\./,"")

simple regex solution. Alternative solution using split:

@.split('.')[-1]
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

JS (ES6), 26 25 bytes

x=>/\.([^.]+)$/.exec(x)[1]

-1 byte thanks to Shaggy

document.querySelector('pre').innerText = (x=>/\.([^.]+)$/.exec(x)[1])("example.txt")
<input oninput = "document.querySelector('pre').innerText = (x=>x.match(/\.([^.]+)$/)[1])(this.value)" value = "example.txt">
<pre></pre>

Alternate, 29 bytes:

x=>(y=x.split`.`)[y.length-1]
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Rulw seem allow x=>/\.[^.]+$/.exec(x) \$\endgroup\$ – l4m2 Mar 15 '18 at 19:45
2
\$\begingroup\$

K (oK), 6 bytes

Solution:

*|"."\

Try it online!

Examples:

*|"."\"whats.up.txt"
"txt"
  *|"."\"T00M@n3KaPZ.h0wC[]h"
"h0wC[]h"

Explanation:

Split \ the input on ".", reverse | this list, and then take the first * one. K is interpreted right-to-left:

*|"."\ / the solution
  "."\ / "." split (\),
 |     / reverse
*      / first
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ohm v2, 5 bytes

I..ï⁾

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Perl 5, 8 bytes

7 bytes code + 1 for -p.

s;.*\.;

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

C# (Visual C# Interactive Compiler), 22 bytes

s=>s.Split('.').Last()

Implicit using System.Linq; FTW!

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

C#, 47 34 27 bytes

System.IO.Path.GetExtension

Saved 6 bytes thanks to @totallyhuman.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Since it's a built in I think you don't need the lambda. System.IO.Path.GetExtension. \$\endgroup\$ – milk May 18 '17 at 0:57
  • \$\begingroup\$ @milk Of course I do, that's just a method, it won't return .ext from file.ext because with just a method there's no way of passing the file.ext in. \$\endgroup\$ – TheLethalCoder May 18 '17 at 7:51
  • 1
    \$\begingroup\$ This is all you have to do. \$\endgroup\$ – totallyhuman Mar 11 '18 at 14:50
  • \$\begingroup\$ @totallyhuman Thanks, saved another byte by dropping the trailing semi colon to. \$\endgroup\$ – TheLethalCoder Mar 12 '18 at 9:03
2
\$\begingroup\$

JavaScript, 21 bytes

x=>x.split('.').pop()

Explanation:

This code takes x.txt and turns it into a array. The last element of the array is the file type. This code uses the pop function to remove the last element. In the process, the pop function returns the last element.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ +Dennis, I have turned it into a arrow function. Does this comply with the rules? \$\endgroup\$ – Tarryk Ttmm Mar 13 '18 at 0:15
  • \$\begingroup\$ Yes, it is fine now. :) By the way, StackExchange uses @ to ping people, not +. \$\endgroup\$ – Dennis Mar 13 '18 at 0:18
  • 2
    \$\begingroup\$ Save 2 bytes with x=>x.split`.`.pop(). \$\endgroup\$ – Grant Miller Mar 14 '18 at 2:02
2
\$\begingroup\$

Python 3, 46 bytes

-8 bytes thanks to Wheat Wizard and Scrooble

import sys
print(sys.argv[1].split('.')[-1])

EDIT: I fixed the code, and the filename is a command-line argument

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to the site! This doesn't appear to work, so you should either fix, or delete this answer. \$\endgroup\$ – caird coinheringaahing Mar 11 '18 at 17:55
  • \$\begingroup\$ This works for 54 \$\endgroup\$ – NoOneIsHere Mar 11 '18 at 17:57
  • \$\begingroup\$ To get the last item of a list you can use -1 as the index instead of len(a)-1. You could also probably change your input format to reduce the number of bytes. \$\endgroup\$ – Wheat Wizard Mar 11 '18 at 18:21
  • \$\begingroup\$ Adding to WW's suggestion: if you use -1 rather than len(a)-1, you no longer need the assignment and can save quite a few bytes. \$\endgroup\$ – Khuldraeseth na'Barya Mar 11 '18 at 21:12
2
\$\begingroup\$

Kotlin, 17 bytes

split(".").last()

Beautified

split(".").last()

Test

data class Test(val input: String, val output: String)

val test = listOf(
        Test("hi.txt", "txt"),
        Test("carrot.meme", "meme"),
        Test("what..is..this..file", "file"),
        Test(".bashrc", "bashrc"),
        Test("T00M@n3KaPZ.h0wC[]h", "h0wC[]h"),
        Test("agent.000", "000")
)

fun String.f() =
split(".").last()

fun main(args: Array<String>) {
    for ((i, o) in test) {
        if (o != i.f()) {
            throw AssertionError()
        }
    }
}

TIO

TryItOnline

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

FORTRAN 90, 87 bytes

CHARACTER(99)F,L
READ*,F;DO I=1,LEN(F)
IF(F(I:I)=='.')L=F(I:LEN(F))
ENDDO
PRINT*,L
END

A shorter version in FORTRAN 90.


FORTRAN 77, 137 bytes

      PROGRAMC;IMPLICITCHARACTER*99(F)
      READ*,F;DOI=LEN(F),1,-1;IF(F(I:I).EQ.'.')THEN
      PRINT*,F(I:LEN(F));EXIT;ENDIF;ENDDO;END

There is no space in PROGRAM C, nor in IMPLICIT CHARACTER. It works (!) in gfortran, but I'm not sure it works in others compilers. The program takes input from stdin and outputs the extension with the period. The total length of the file name is limited by 99.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

V, 4 bytes

òdt.

Try it online!

Recursively delete everything up to, but not including the next .

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

C++, 73 bytes

I'm a bit surprised that no one tried C++, since it's an easy one :

#include<string>
auto e=[](std::string s){return s.substr(s.rfind(46));};

And the code to test ( may have to iostream, initializer_list, and exception ) :

std::initializer_list<std::string> test{
    "hi.txt", // .txt
    "carrot.meme", // .meme
    "lol", // invalid string position
    "what..is..this..file", // .file
    ".bashrc", // .bashrc
    "T00M@n3KaPZ.h0wC[]h", // .h0wC[]h
    "agent.000" // .000
};

for (const auto& a : test) {
    try {
        std::cout << e(a) << '\n';
    }
    catch (std::out_of_range& r) {
        std::cout << "out of range exception : " << r.what() << '\n';
    }
}

And, as you may expect, like compilers, if there's undefined behavior, there's no undefined behavior. If there's no file extension, the function will throw a std::out_of_range exception, as said in cppreference

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

SmileBASIC, 45 bytes

INPUT S$@L
E$=POP(S$)+E$ON"."==E$[0]GOTO@L?E$

Outputs extension with the period.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Arn, 6 bytes

Ê^!⁺╔d

Try it!

Explained

Unpacked: :!".":}

    _ Variable initialized to STDIN; implied
  :! Split on
    "." String containing a period
:} Tail
| improve this answer | |
\$\endgroup\$
2
+100
\$\begingroup\$

APL (Dyalog Unicode), 10 bytes (SBCS)

⊃∘⌽'.'∘≠⊆⊢

-7 bytes after Bubbler's suggestion.

Try it online!

APL (Dyalog Unicode), 17 bytes (SBCS)

⊃⌽'.'(1↓¨,⊂⍨⊣=,)⍞

Explanation

⊃⌽'.'(1↓¨,⊂⍨⊣=,)⍞
                ⍞ string input
            ⊣=,)  get characters, evaluate if they are equal to the left arg '.'
         ,⊂⍨      enclose each part after a dot
  '.'(1↓¨         drop each dot in the strings
 ⌽                reverse the split string array
⊃                 take the first value

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Including the dot is allowed (so you don't need 1↓¨), but then, you can use ≠⊆⊢ idiom to split the words at dots, excluding dots. \$\endgroup\$ – Bubbler Aug 28 at 7:11
  • \$\begingroup\$ Then the tacit ⊃∘⌽'.'∘≠⊆⊢ is one byte shorter than full program ⊃⌽'.'(≠⊆⊢)⍞. \$\endgroup\$ – Bubbler Aug 28 at 7:20
  • \$\begingroup\$ interesting. I'll try it out. How do it get it to work on TIO? \$\endgroup\$ – Razetime Aug 28 at 7:26
  • \$\begingroup\$ No different from other function submissions. \$\endgroup\$ – Bubbler Aug 28 at 7:35
2
\$\begingroup\$

Python3 (32 bytes)

f=input()
print(f[f.rfind('.'):])

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Welcome to the site. You might like to include a link to Try it online! in your answer. TIO is widely used here because it's quite handy: not only does it let other people try out your code, it also creates pre-formatted CGCC submissions for you. \$\endgroup\$ – Dingus Aug 29 at 9:32
2
\$\begingroup\$

33 v1.0, 13 bytes

The behaviour of the y operator was changed in v1.1, so this program no longer works

Gets the file name passed as an argument and prints the extension (without leading '.') to standard output.

1bt'.'ywmcbtp

Explanation:

1b            (Gets the second item in argv, the filename input)
  t'.'y       (Splits that by '.')
       wmcb   (Gets the last element in the list)
           tp (Prints to standard output)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 2, 25 bytes

lambda s:s.split('.')[-1]

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Groovy, 37 bytes

{it.substring(it.lastIndexOf(".")+1)}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ How did someone already upvote this lol. Literally 1 second after I hit submit it hit +1. \$\endgroup\$ – Magic Octopus Urn May 16 '17 at 21:04
1
\$\begingroup\$

Ruby, 21 bytes

->f{f.split('.')[-1]}

12 bytes

File.extname
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Tcl, 21 bytes

puts [file ext $argv]

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Julia, 22 bytes

g(n)=split(n,'.')[end]
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Ruby, 16 bytes

->s{s[/[^.]+$/]}

Try it online!

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.