10
\$\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\$
  • 17
    \$\begingroup\$ Please consider using the Sandbox in the future to get feedback on your challenges before posting them to the main site. \$\endgroup\$ – Mego 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
  • 1
    \$\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

86 Answers 86

2
\$\begingroup\$

Pyth, 5 bytes

ecz\.

try it here

\$\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
\$\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)
\$\endgroup\$
2
\$\begingroup\$

C#, 35 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Haskell, 32 30 29 bytes

-1 byte thanks to Laikoni

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

self-explanatory

\$\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]
\$\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]
\$\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
\$\endgroup\$
2
\$\begingroup\$

Ohm v2, 5 bytes

I..ï⁾

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Perl 5, 8 bytes

7 bytes code + 1 for -p.

s;.*\.;

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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

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

Implicit using System.Linq; FTW!

Try it online!

\$\endgroup\$
2
\$\begingroup\$

C#, 47 34 27 bytes

System.IO.Path.GetExtension

Saved 6 bytes thanks to @totallyhuman.

Try it online!

\$\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.

\$\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

\$\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

\$\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.

\$\endgroup\$
2
\$\begingroup\$

V, 4 bytes

òdt.

Try it online!

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

\$\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

\$\endgroup\$
2
\$\begingroup\$

SmileBASIC, 45 bytes

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

Outputs extension with the period.

\$\endgroup\$
2
\$\begingroup\$

PowerShell, 34 26 bytes

-8 bytes thanks to @mazzy

(Read-Host).Split('.')[-1]

Takes input from STDIN. Actually managed to golf it down shorter than the built-in.

PowerShell, 20 bytes

($args-split'.')[-1]

Takes input from commandline arguments. Big thanks to @mazzy again!

PowerShell (with built-in), 36 bytes

[IO.Path]::GetExtension((Read-Host))
\$\endgroup\$
1
\$\begingroup\$

Python 2, 25 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Groovy, 37 bytes

{it.substring(it.lastIndexOf(".")+1)}
\$\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
\$\endgroup\$
1
\$\begingroup\$

Tcl, 21 bytes

puts [file ext $argv]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Julia, 22 bytes

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

Ruby, 16 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Excel, 58 bytes

=TRIM(RIGHT(SUBSTITUTE(A1,".",REPT(" ",LEN(A1))),LEN(A1)))
\$\endgroup\$
1
\$\begingroup\$

Excel VBA, 29 bytes

An anonymous VBE immediate window function that takes input via cell [A1] and outputs to the console. Return string is of the form .Extension.

?Mid([A1],InStrRev([A1],"."))
\$\endgroup\$
1
\$\begingroup\$

Yabasic, 34 bytes

A answer

Takes input as a string from STDIN, and outputs of the form .Extension to STDOUT.

Input""s$
?Mid$(s$,RInStr(s$,"."))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Google Sheets, 25 bytes

An anonymous worksheet function that takes input from cell A1 and outputs the detected file extension of the form Extension to the calling cell.

=RegexExtract(A1,"[^\.]+$
\$\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.