What's the file extension?

10

5

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^!\[\]{}@$%+=]+$.

programmer5000

Posted 2017-05-16T20:35:37.283

Reputation: 7 828

17

Please consider using the Sandbox in the future to get feedback on your challenges before posting them to the main site.

– Mego – 2017-05-16T20:45:43.210

1https://codegolf.meta.stackexchange.com/a/12432/59376 - Got this idea from your challenge. – Magic Octopus Urn – 2017-05-16T21:51:19.607

@carusocomputing nice challenge! – programmer5000 – 2017-05-17T00:06:53.463

1why the negative votes? Is this challenge "exceedingly trivial" or so ? – Abel Tom – 2017-05-17T05:09:40.793

@AbelTom edit history would suggest downvotes were for the lack of specifications in the first draft of this question. – Patrick Roberts – 2017-05-17T05:12:29.793

@Arjun the downvote count seems to be slowly increasing. I have no idea why. – programmer5000 – 2017-05-18T11:22:31.483

Answers

15

Retina, 5 bytes

.*\.

Replaces everything and a dot with nothing at all.

Try it online!

John Dvorak

Posted 2017-05-16T20:35:37.283

Reputation: 9 048

11

JavaScript (ES6), 19 bytes

Returns the full filename when there's no file extension. I suppose this is an acceptable undefined behavior.

let f =

s=>s.split`.`.pop()

console.log(f("hi.txt"))               // -> txt
console.log(f("carrot.meme"))          // -> meme
console.log(f("lol"))                  // -> undefined behavior
console.log(f("what..is..this..file")) // -> file
console.log(f("T00M@n3KaPZ.h0wC[]h")) // -> h0wC[]h
console.log(f(".bashrc")) // -> bashrc

Arnauld

Posted 2017-05-16T20:35:37.283

Reputation: 111 334

The point of undefined behavior is that anything goes. Although, nasal demons, while still undefined behavior, might fail the "no malicious programs" clause. – John Dvorak – 2017-05-27T11:26:45.613

10

Mathematica, 13 22 bytes

Edit: Not sure how I missed the ".bashrc" test case. Thanks to Artyer for keeping me honest.

FileExtension["a"<>#]&

If the input matches \.[^.]+, then FileExtension just returns the empty string, so we prepend the letter a. In any other case, prepending a doesn't affect output of FileExtension.

ngenisis

Posted 2017-05-16T20:35:37.283

Reputation: 4 600

11A Mathematica builtin...no surprise. – programmer5000 – 2017-05-16T21:03:58.517

1I'd be surprised if there weren't any mathematica builtins for any question possible – sagiksp – 2017-05-17T05:52:28.927

I don't have access to Mathematica, but I would suspect that .ext would result in nothing, which failes for .bashrc needing to output bashrc (It fails in Mathics)

– Artyer – 2017-05-17T11:22:33.197

Apparently it works – programmer5000 – 2017-05-17T11:36:35.173

Mathematica just needs to meta built-ins Create Built-in XXXXXXXX. – Magic Octopus Urn – 2017-05-17T13:02:24.880

@Artyer You are correct. – ngenisis – 2017-05-17T16:09:53.080

@MagicOctopusUrn Do you mean the Wolfram Function Repository? Just get your code approved there, and you can refer to it while golfing!

– Roman – 2019-07-25T05:31:01.360

9

Pure bash, 13

echo ${1##*.}

Try it online.

Digital Trauma

Posted 2017-05-16T20:35:37.283

Reputation: 64 644

7

05AB1E, 4 bytes

'.¡¤

Try it online! or Try All Tests

'.   # Push '.'
  ¡  # Split on occurrences of '.'
   ¤ # Tail

Riley

Posted 2017-05-16T20:35:37.283

Reputation: 11 345

What? I've never seen a split occurences in the wiki. Edit: Now I found it!

– facepalm42 – 2019-07-18T11:09:39.480

7

Japt, 3 bytes

2 bytes of code, +1 for the h flag.

q.

Explanation:

q.       Split the input by `.`
   -h    Return the last item

Try it online!

Oliver

Posted 2017-05-16T20:35:37.283

Reputation: 7 160

7

c function, 21

  • 1 byte saved thanks to @Dennis.
  • 3 bytes saved thanks to @JohanduToit.
  • 2 bytes saved thanks to @Neil.
  • 1 byte saved thanks to @algmyr.
f(s){s=rindex(s,46);}

Try it online.

Digital Trauma

Posted 2017-05-16T20:35:37.283

Reputation: 64 644

1If you're ok with using legacy POSIX functions you could use rindex to save a byte. – algmyr – 2017-05-17T19:15:18.650

@algmyr Sure, it works fine on TIO, so I'll use it. I'd never heard of rindex() before - thanks for the tip! – Digital Trauma – 2017-05-17T19:34:14.913

5

PHP, 21 Bytes

<?=pathinfo($argn,4);

Try it online!

is a shorter expression for

<?=pathinfo($argn)[extension];

pathinfo

PHP, 27 Bytes

<?=end(explode(".",$argn));

explode

Try it online!

PHP <7.0, 26 Bytes

<?=end(split("\.",$argn));

deprecated split

Jörg Hülsermann

Posted 2017-05-16T20:35:37.283

Reputation: 13 026

1Are you counting a trailing newline for the first one? It should be 27 bytes, not 28. – Conor O'Brien – 2017-05-16T21:45:03.083

@ConorO'Brien Thank You .I have count after copy and paste from the split version a \ – Jörg Hülsermann – 2017-05-16T21:49:16.727

2The pathinfo() based one could be <?=pathinfo($argn,4);. – manatwork – 2017-05-17T11:56:40.230

4

V, 5, 3 bytes

Since more of this answer is unprintable than printable, here is a hexdump:

00000000: cd81 ae                                  ...

Try it online!

This uses Jan Dvorak's algorithm, it just happens to be a more efficient encoding of it.

Explanation:

Í       " Remove all occurrences of:
 0x81   "   Anything (greedy)
     ®  "   Followed by a dot 

Old solution:

$T.d|

James

Posted 2017-05-16T20:35:37.283

Reputation: 54 537

Explanation please? – Erik the Outgolfer – 2017-05-17T13:18:17.933

@EriktheOutgolfer Done – James – 2017-05-17T16:39:50.217

Wait ® means followed by a dot? Lol that's weird. – Erik the Outgolfer – 2017-05-17T16:42:19.007

4

Neo4j Cypher, 24 bytes

return split($i,".")[-1]

Input is in a param (i), probably the only way for cypher to take input. Pretty straightforward. Cypher has never been used on PPCG before

programmer5000

Posted 2017-05-16T20:35:37.283

Reputation: 7 828

4

GNU Make, 12 bytes

$(suffix $1)

Not using a builtin, 27 bytes:

$(lastword $(subst ., ,$1))

eush77

Posted 2017-05-16T20:35:37.283

Reputation: 1 280

4

Batch, 10 bytes

@echo %~x1

Strangely competitive for once.

Neil

Posted 2017-05-16T20:35:37.283

Reputation: 95 035

3

JavaScript (ES6), 33 31 28 bytes

s=>s.slice(s.lastIndexOf`.`)

Spec change in comments removes the need for +1.

-3 bytes thanks to nderscore

Stephen

Posted 2017-05-16T20:35:37.283

Reputation: 12 293

1-3 with slice and template string execution: s=>s.slice(s.lastIndexOf\.`)` – nderscore – 2017-05-16T21:42:57.760

3

Jelly, 4 bytes

ṣ”.Ṫ

A monadic link taking the file name and returning the extension with no leading ..

Try it online!

How?

Literally does what was asked...

ṣ”.Ṫ - Main link: list of characters, f
 ”.  - literal '.'
ṣ    - split f at occurrences of '.'
   Ṫ - tail (get the last chunk)

Jonathan Allan

Posted 2017-05-16T20:35:37.283

Reputation: 67 804

3

sed, 8 bytes

s:.*\.::

Try it online!

eush77

Posted 2017-05-16T20:35:37.283

Reputation: 1 280

3

Go, 85 bytes

Go is... troublesome.

import(."fmt"
."os"
."strings")
func main(){s:=Split(Args[1],".");Print(s[len(s)-1])}

Try it online!

A sample of parentheses from the code:

()(){([])([()])}

totallyhuman

Posted 2017-05-16T20:35:37.283

Reputation: 15 378

2()(){([])([()])} — is it a valid Brain-Flak? – eush77 – 2017-05-16T21:08:53.180

5@eush77 It's technically valid Brain-Flak, since it will run without errors, but it doesn't do anything interesting/useful. It's either just the literal 2 with no instructions/commands or anything or an infinite loop that continuously allocates more memory, depending on input. – James – 2017-05-16T21:27:17.723

Using filepath.Ext will save you a few bites – powelles – 2017-05-16T22:17:53.800

3

Javascript (ES5), 38 bytes

function(s){return s.split(".").pop()}

Sinned

Posted 2017-05-16T20:35:37.283

Reputation: 29

2

Just so you know, the downvote was cast automatically by the Community user when your answer was edited. I consider this a bug.

– Dennis – 2017-05-16T22:57:12.530

plz fix that if you can! – Sinned – 2017-05-17T00:56:06.350

3

Common Lisp, 57 bytes

(lambda(s)(#1=reverse(subseq #2=(#1# s)0(search"."#2#))))

Try it online (added some bytes to call this anonymous function and display returned string)

Explanation

(#1=reverse ...)     ;reverse is now accessible with #1# - saves 1 byte. I 
                     ;also need to reverse output of function inside to 
                     ;get extension in correct order
#2=(#1# s)           ;reverse of input string is now accessible with #2#
(search"."#2#)       ;I take reversed string and search for "." to get position of 
                     ;first instance of "." in string from the end of it
(subseq ... 0 ...)   ;get part of reversed string, 
                     ;starting from first character and ending just 
                     ;before first occurance of "."
                     ;this gives reversed extension

I get substring of reversed string, starting from 0, ending on this

user65167

Posted 2017-05-16T20:35:37.283

Reputation:

3

C#, 33 41 bytes

a=>a.Split('.').Last();

Edit as suggested:

using System.Linq;a=>a.Split('.').Last();

LiefdeWen

Posted 2017-05-16T20:35:37.283

Reputation: 3 381

1You need to include using Sytem.Linq; into your byte count – TheLethalCoder – 2017-05-17T12:17:54.690

And also a=>a.Split('.').Last(); implicit return is shorter – TheLethalCoder – 2017-05-17T12:18:22.723

@TheLethalCoder Thanks for suggested fixes, still new to this :) – LiefdeWen – 2017-05-17T12:23:39.390

I'm surprised this is longer than my solution using Path... – TheLethalCoder – 2017-05-17T13:03:07.913

3

Java 8, 52 27 bytes

s->s.replaceAll(".*\\.","")

Try it here.

Replace everything before the last dot (and the dot itself) with nothing.

This is shorter than using split (s->s.split("\\.")[s.split("\\.").length-1];) or substring (s->s.substring(s.lastIndexOf('.'));).

Kevin Cruijssen

Posted 2017-05-16T20:35:37.283

Reputation: 67 575

3

Gema, 3 characters

*.=

Sample run:

bash-4.4$ gema '*.=' <<< 'what..is..this..file'
file

manatwork

Posted 2017-05-16T20:35:37.283

Reputation: 17 865

3

MATL, 8 7 bytes

46&YbO)

Try it at MATL Online!

Explanation

        % Implicitly grab input as string
46      % ASCII for '.'
&Yb     % Split the input string at the '.' characters
O)      % Retrieve just the last part
        % Implicitly print the result

Suever

Posted 2017-05-16T20:35:37.283

Reputation: 10 257

3

Awk, 14 13 characters

(10 9 characters code + 4 characters command line option.)

{$0=$NF}1

Thanks to:

  • Robert Benson for spotting the unnecessary semicolon (-1 character)

Sample run:

bash-4.4$ awk -F. '{$0=$NF}1' <<< $'hi.txt\ncarrot.meme\nlol\nwhat..is..this..file\n.bashrc\nT00M@n3KaPZ.h0wC[]h'
txt
meme
lol
file
bashrc
h0wC[]h

manatwork

Posted 2017-05-16T20:35:37.283

Reputation: 17 865

You don't need the ;. and just FYI, awk '{$0=$NF}1 works, no command line option needed. Oh... I must be tired. I see what you did there. You do need the command line option. – Robert Benson – 2017-05-17T18:18:40.277

1Thank you, @RobertBenson. I have no idea why I put that ; there. – manatwork – 2017-05-17T18:53:18.483

3

Lua, 53 30 bytes

Replaces everything upto the last . with the empty string ''.

Double parenthesis to select only the first return value of gsub.

Any golfing tips are welcome, I'm rusty in lua...

print(((...):gsub('.*%.','')))

Try it online!

Felipe Nardi Batista

Posted 2017-05-16T20:35:37.283

Reputation: 2 345

3

Vim, 5 bytes

$F.d0

Explanation: find last . in line, delete everything before it

Another, longer, but in my opinion still interesting approach with 9 bytes (notice the trailing new line)

d/.*\./e

This one works similarly, 5 bytes (again, trailing new line):

d?\.

oktupol

Posted 2017-05-16T20:35:37.283

Reputation: 697

3

Taxi, 1397 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[a]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan "b" if no one is waiting.Switch to plan "a".[b]Go to The Babelfishery:n 1 l 1 l.[c]Go to Fueler Up:n.Go to Joyless Park:n 2 r.Go to Narrow Path Park:w 1 r 3 l.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 l 1 r 2 l.Pickup a passenger going to Crime Lab.Pickup a passenger going to Joyless Park.'.' is waiting at Writer's Depot.Go to Writer's Depot:s.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "c" if no one is waiting.Go to Narrow Path Park:n 5 l.[d]Pickup a passenger going to Chop Suey.Go to Chop Suey:e 1 r 1 l 1 r.Go to Narrow Path Park:n 1 l 1 r 1 l.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Joyless Park:e 1 r 3 l.Switch to plan "f" if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Fueler Up:w 1 l.Go to Narrow Path Park:n 4 l.Switch to plan "e".[f]Go to Narrow Path Park:w 1 r 3 l.[g]Switch to plan "h" if no one is waiting.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 2 l.Switch to plan "g".[h]Go to KonKat's:e 1 r.Pickup a passenger going to Post Office.Go to Post Office:s 3 r 1 l.

Try it online!

Taxi doesn't have a reverse function so this ballooned pretty quickly. The logic is:

  1. Break the string into characters
  2. Reverse the array
  3. Iterate through each until a period is found, storing each in a FIFO array
  4. Empty the array (because there's only one LIFO array available)
  5. Dump the FIFO array into the LIFO array
  6. Concatenate the LIFO array and output

Engineer Toast

Posted 2017-05-16T20:35:37.283

Reputation: 5 769

2

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]

programmer5000

Posted 2017-05-16T20:35:37.283

Reputation: 7 828

Rulw seem allow x=>/\.[^.]+$/.exec(x) – l4m2 – 2018-03-15T19:45:57.920

2

Brain-Flak, 84 bytes

Includes +2 for -rc

(()){{}([((((()()()){}())()){}{}){}]({}<>)<>)({()(<{}>)}{})}{}{{}}<>{}{({}<>)<>}<>

Try it online!

# Push 1 to start the loop
(())

# Start loop
{{}

  # If TOS == 46 i.e. '.'
  ([((((()()()){}())()){}{}){}]({}<>)<>)({()(<{}>)}{})
  # ^------------------------^ ^-------^ 
  #           This is 46         Also, copy TOS to other stack

# End loop after the first '.'
}{}

# Delete everything from this stack
{{}}

# Delete the '.' that got copied
<>{}

# Copy everything back to reverse it to the correct order
{({}<>)<>}<>

Riley

Posted 2017-05-16T20:35:37.283

Reputation: 11 345

2

Japt, 6 5 bytes

q'. o

Try it online!

Explanation

 q'. o
Uq'. o
Uq'.    # Split the input at "."
     o # Return the last item

Luke

Posted 2017-05-16T20:35:37.283

Reputation: 4 675

When you only need to return the last item of an array, you can use o in place of gJ. (Learned that trick from @obarakon a while back) – ETHproductions – 2017-05-16T23:38:30.840

2

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

ASCII-only

Posted 2017-05-16T20:35:37.283

Reputation: 4 687

Can't you use ⊟x instead of §x±¹? – Erik the Outgolfer – 2017-05-17T13:13:56.700

2

jq, 15 14 characters

(11 10 characters code + 4 characters command line options.)

./"."|last

Sample run:

bash-4.4$ jq -Rr './"."|last' <<< 'what..is..this..file'
file

On-line test

manatwork

Posted 2017-05-16T20:35:37.283

Reputation: 17 865

2

Octave, 24 bytes

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

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

Online Demo

Suever

Posted 2017-05-16T20:35:37.283

Reputation: 10 257

2

C#, 47 34 27 bytes

System.IO.Path.GetExtension

Saved 6 bytes thanks to @totallyhuman.

Try it online!

TheLethalCoder

Posted 2017-05-16T20:35:37.283

Reputation: 6 930

Since it's a built in I think you don't need the lambda. System.IO.Path.GetExtension. – milk – 2017-05-18T00:57:09.640

@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. – TheLethalCoder – 2017-05-18T07:51:26.293

1This is all you have to do. – totallyhuman – 2018-03-11T14:50:27.197

@totallyhuman Thanks, saved another byte by dropping the trailing semi colon to. – TheLethalCoder – 2018-03-12T09:03:25.603

2

Pyth, 5 bytes

ecz\.

try it here

Erik the Outgolfer

Posted 2017-05-16T20:35:37.283

Reputation: 38 134

2

REXX 53

parse value reverse(arg(1)) with e "." 
say reverse(e)

theblitz

Posted 2017-05-16T20:35:37.283

Reputation: 1 201

2

C#, 35 bytes

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

Try it online!

TheLethalCoder

Posted 2017-05-16T20:35:37.283

Reputation: 6 930

2

Haskell, 32 30 29 bytes

-1 byte thanks to Laikoni

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

self-explanatory

Julian Wolf

Posted 2017-05-16T20:35:37.283

Reputation: 1 139

1takeWhile can be shortened to fst.span. – Laikoni – 2017-05-17T16:17:52.953

2

Cheddar, 16 bytes

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

simple regex solution. Alternative solution using split:

@.split('.')[-1]

Downgoat

Posted 2017-05-16T20:35:37.283

Reputation: 27 116

2

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

streetster

Posted 2017-05-16T20:35:37.283

Reputation: 3 635

2

Ohm v2, 5 bytes

I..ï⁾

Try it online!

Cinaski

Posted 2017-05-16T20:35:37.283

Reputation: 1 588

2

Perl 5, 8 bytes

7 bytes code + 1 for -p.

s;.*\.;

Try it online!

Dom Hastings

Posted 2017-05-16T20:35:37.283

Reputation: 16 415

2

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.

Tarryk Ttmm

Posted 2017-05-16T20:35:37.283

Reputation: 21

+Dennis, I have turned it into a arrow function. Does this comply with the rules? – Tarryk Ttmm – 2018-03-13T00:15:18.427

Yes, it is fine now. :) By the way, StackExchange uses @ to ping people, not +. – Dennis – 2018-03-13T00:18:18.390

2Save 2 bytes with x=>x.split`.`.pop(). – Grant Miller – 2018-03-14T02:02:38.797

2

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

sirtomato999

Posted 2017-05-16T20:35:37.283

Reputation: 21

1

Welcome to the site! This doesn't appear to work, so you should either fix, or delete this answer.

– caird coinheringaahing – 2018-03-11T17:55:06.757

This works for 54 – NoOneIsHere – 2018-03-11T17:57:08.387

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. – Post Rock Garf Hunter – 2018-03-11T18:21:51.133

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. – Khuldraeseth na'Barya – 2018-03-11T21:12:19.803

2

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

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

Implicit using System.Linq; FTW!

Try it online!

Pavel

Posted 2017-05-16T20:35:37.283

Reputation: 8 585

2

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.

rafa11111

Posted 2017-05-16T20:35:37.283

Reputation: 310

2

SmileBASIC, 45 bytes

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

Outputs extension with the period.

12Me21

Posted 2017-05-16T20:35:37.283

Reputation: 6 110

2

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

jrtapsell

Posted 2017-05-16T20:35:37.283

Reputation: 915

2

V, 4 bytes

òdt.

Try it online!

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

oktupol

Posted 2017-05-16T20:35:37.283

Reputation: 697

2

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

HatsuPointerKun

Posted 2017-05-16T20:35:37.283

Reputation: 1 891

2

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

Gabriel Mills

Posted 2017-05-16T20:35:37.283

Reputation: 778

1

you can save some bytes. try this ($args-split'.')[-1] see About Automatic Variables

– mazzy – 2018-10-26T16:38:34.507

1

Python 2, 25 bytes

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

Try it online!

totallyhuman

Posted 2017-05-16T20:35:37.283

Reputation: 15 378

1

Groovy, 37 bytes

{it.substring(it.lastIndexOf(".")+1)}

Magic Octopus Urn

Posted 2017-05-16T20:35:37.283

Reputation: 19 422

How did someone already upvote this lol. Literally 1 second after I hit submit it hit +1. – Magic Octopus Urn – 2017-05-16T21:04:14.127

1

Ruby, 21 bytes

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

12 bytes

File.extname

marmeladze

Posted 2017-05-16T20:35:37.283

Reputation: 227

1

C (gcc), 77 60 52 bytes

char*f(char*s){for(s+=strlen(s);*--s-46;);return s;}

Try it online!

-17 bytes from Jonathan Frech

-8 bytes by removing i and doing arithmetic on s directly

Ungolfed (same strategy):

char *extension(char *original) {
    original = original + strlen(original);
    while(original[0] != '.') --original;
    return original;
}

pizzapants184

Posted 2017-05-16T20:35:37.283

Reputation: 3 174

60 bytes. – Jonathan Frech – 2017-10-29T19:06:06.397

24 bytes – ceilingcat – 2019-11-02T08:01:24.910

1

Tcl, 21 bytes

puts [file ext $argv]

Try it online!

sergiol

Posted 2017-05-16T20:35:37.283

Reputation: 3 055

1

Julia, 22 bytes

g(n)=split(n,'.')[end]

EricShermanCS

Posted 2017-05-16T20:35:37.283

Reputation: 121

1

Ruby, 16 bytes

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

Try it online!

daniero

Posted 2017-05-16T20:35:37.283

Reputation: 17 193

1

Excel, 58 bytes

=TRIM(RIGHT(SUBSTITUTE(A1,".",REPT(" ",LEN(A1))),LEN(A1)))

Wernisch

Posted 2017-05-16T20:35:37.283

Reputation: 2 534

1

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],"."))

Taylor Scott

Posted 2017-05-16T20:35:37.283

Reputation: 6 709

1

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!

Taylor Scott

Posted 2017-05-16T20:35:37.283

Reputation: 6 709

1

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

Taylor Scott

Posted 2017-05-16T20:35:37.283

Reputation: 6 709

1

><>, 50 bytes

i:0( ?v
v[:<2~<
r  ^]+1r<
>:"."=?v^
v?l<r~r<;
>o ^

Try it online!

hakr14

Posted 2017-05-16T20:35:37.283

Reputation: 1 295

1

ActionScript 2.0, 42 bytes

function a(b){trace(b.split(".").pop());};

Technically the ;s aren't required for it to compile, at least in JPEXS, but it's good practice. Call:

a("a.b");

(traces "b")

Jhynjhiruu Rekrap

Posted 2017-05-16T20:35:37.283

Reputation: 61

Oh, OK. Looking at other examples, I didn't realise that. ActionScript doesn't really have a way to take inputs, so sure, delete this. Unless... – Jhynjhiruu Rekrap – 2018-03-09T20:28:19.250

Looks good. Happy golfing. – 0 ' – 2018-03-09T20:36:48.053

Awesome. By the way, putting the trace() inside the function is shorter when considering outputting, but then it requires a string be included when calling the function - is that allowed? – Jhynjhiruu Rekrap – 2018-03-09T20:39:10.443

I'm not quite sure what you mean by it requiring a string to be included when calling the function as I hardly know any Actionscript. In general it's allowed to mix and match any of the default allowed input and output methods. – 0 ' – 2018-03-09T20:54:27.383

function a(b){trace(b.split(".").pop());}; prints the output and is only 42 bytes, but calling the function would be a("a.b"); ActionScript has syntax very similar to JavaScript, so you can pretty much just read it like JavaScript. – Jhynjhiruu Rekrap – 2018-03-09T20:55:56.163

If that is valid Actionscript then I think that would be fine. The only thing is that it is not actually shorter (nor is it longer) than what you currently have so you can use whichever you like without an impact on your score. – 0 ' – 2018-03-09T20:58:20.117

Let us continue this discussion in chat.

– Jhynjhiruu Rekrap – 2018-03-09T20:59:21.573

1

CJam, 6 bytes

q'./W=

Try it online!

        Print
    W     the last
     =    element
   /      of the result of splitting
q         the input
 '.       on the character '.'

Esolanging Fruit

Posted 2017-05-16T20:35:37.283

Reputation: 13 542

1

Add++, 9 bytes

L,"."$tbU

Try it online!

caird coinheringaahing

Posted 2017-05-16T20:35:37.283

Reputation: 13 702

1

Aceto, 6 bytes

r'.:Qp

Try it online!

r       grabs input as string
 '.     literal period
   :    split string on period
    Q   grap bottom item
     p  print it

drham

Posted 2017-05-16T20:35:37.283

Reputation: 515

1

><>, 18 bytes

i:0(6$.:"."=?]
ro|

Try it online!

How It Works:

i:(6$.  Jump to the second line if out of input
      :"."=  Else check if the character is a .
           ?[ And create a new stack if it is
              Loop back to the beginning of the line
If it is end of input
ro|  Reverse the current stack once and output, erroring on the EOF (-1)

Jo King

Posted 2017-05-16T20:35:37.283

Reputation: 38 234

1

Stax, 4 bytes

'./H

Run and debug online!

Explanation

Split on ., take last part.

Weijun Zhou

Posted 2017-05-16T20:35:37.283

Reputation: 3 396

1

T-SQL, 48 bytes

SELECT RIGHT(F,CHARINDEX('.',REVERSE(F))) FROM T

SQL Fiddle

Razvan Socol

Posted 2017-05-16T20:35:37.283

Reputation: 341

1

SNOBOL4 (CSNOBOL4), 46 bytes

	I =INPUT
S	I '.' REM . I	:S(S)
	OUTPUT =I
END

Try it online!

Takes the input, then repeatedly replaces it with all the text following the first . until no .s remain, then outputs the value.

Giuseppe

Posted 2017-05-16T20:35:37.283

Reputation: 21 077

1

Funky, 26 bytes

s=>(k=s::split".")[(#k)-1]

Try it online!

ATaco

Posted 2017-05-16T20:35:37.283

Reputation: 7 898

1

Jotlin, 17 bytes

split(".").last()

Full file:

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()

for ((i, o) in test) {
    if (o != i.f()) {
        throw AssertionError()
    }
}

jrtapsell

Posted 2017-05-16T20:35:37.283

Reputation: 915

1

R, 40 26 bytes

-14 bytes thanks to J.Doe

sub("^.*[.]","",scan(,""))

Try it online!

Robert S.

Posted 2017-05-16T20:35:37.283

Reputation: 1 253

26 bytes – J.Doe – 2018-10-27T09:16:05.833

1

MBASIC, 129 bytes

1 INPUT F$:F=INSTR(F$,"."):IF F=0 THEN END
2 FOR I=LEN(F$) TO 1 STEP -1:P$=MID$(F$,I,1):O$=P$+O$:IF P$="." THEN PRINT O$:END
3 NEXT

Explanation

Get a filename. If it doesn't contain a period, bail out. Otherwise, collect letters from right to left to build an output string. When we see a period, print the string.

Output

? hi.txt
.txt

? .bashrc
.bashrc

? T00M@n3KaPZ.h0wC[]h
.h0wC[]h

wooshinyobject

Posted 2017-05-16T20:35:37.283

Reputation: 171

1

Red 9 bytes

Suffix? f

Assumes file is is in word 'f

AngryCutlery

Posted 2017-05-16T20:35:37.283

Reputation: 11

2Do you have a link to documentation or interpreters for that language? – Nissa – 2018-10-29T20:35:18.947

I don't think this does what the challenge asks. The challenge is asking for a program that takes the file name and gives the extension. – Post Rock Garf Hunter – 2018-10-29T20:54:37.257

1

Pepe, 48 bytes

rEeeEeEEEeREEeREEEerEEREEEEEEEreererEEEEeEeereee

Try it online!

u_ndefined

Posted 2017-05-16T20:35:37.283

Reputation: 1 253

1

Turing Machine But Way Worse, 1315 1287 bytes

0 0 0 1 1 0 0
1 0 1 1 8 0 0
0 1 0 1 2 0 0
1 1 1 1 9 0 0
0 2 0 1 3 0 0
1 2 1 1 a 0 0
0 3 0 1 4 0 0
1 3 1 1 b 0 0
0 4 0 1 5 0 0
1 4 1 1 c 0 0
0 5 0 1 6 0 0
1 5 1 1 d 0 0
0 6 0 1 7 0 0
1 6 1 1 e 0 0
0 7 0 1 f 0 0
1 7 1 1 0 0 0
0 8 0 1 9 0 0
1 8 1 1 9 0 0
0 9 0 1 a 0 0
1 9 1 1 a 0 0
0 a 0 1 b 0 0
1 a 1 1 b 0 0
0 b 0 1 c 0 0
1 b 1 1 c 0 0
0 c 0 1 d 0 0
1 c 1 1 d 0 0
0 d 0 1 e 0 0
1 d 1 1 e 0 0
0 e 0 1 0 0 0
1 e 1 1 0 0 0
0 f 0 0 g 0 0
1 f 1 0 g 0 0
0 g 0 0 h 0 0
1 g 1 0 p 0 0
0 h 0 0 q 0 0
1 h 1 0 i 0 0
0 i 0 0 r 0 0
1 i 1 0 j 0 0
0 j 0 0 s 0 0
1 j 1 0 k 0 0
0 k 0 0 l 0 0
1 k 1 0 t 0 0
0 l 0 0 u 0 0
1 l 1 0 m 0 0
0 m 0 0 n 0 0
1 m 1 0 v 0 0
0 n 0 0 o 0 0
1 n 1 0 g 0 0
0 p 0 0 q 0 0
1 p 1 0 q 0 0
0 q 0 0 r 0 0
1 q 1 0 r 0 0
0 r 0 0 s 0 0
1 r 1 0 s 0 0
0 s 0 0 t 0 0
1 s 1 0 t 0 0
0 t 0 0 u 0 0
1 t 1 0 u 0 0
0 u 0 0 f 0 0
1 u 1 0 f 0 0
0 o 0 1 w 0 0
1 o 1 1 w 0 0
0 w 0 1 x 0 0
1 w 1 1 E 0 0
0 x 0 1 y 0 0
1 x 1 1 F 0 0
0 y 0 1 z 0 0
1 y 1 1 G 0 0
0 z 0 1 A 0 0
1 z 1 1 H 0 0
0 A 0 1 B 0 0
1 A 1 1 I 0 0
0 B 0 1 C 0 0
1 B 1 1 J 0 0
0 C 0 1 D 0 0
1 C 1 1 K 0 0
0 D 0 1 D 0 1
1 D 1 1 w 1 0
0 E 0 1 F 0 0
1 E 1 1 F 0 0
0 F 0 1 G 0 0
1 F 1 1 G 0 0
0 G 0 1 H 0 0
1 G 1 1 H 0 0
0 H 0 1 I 0 0
1 H 1 1 I 0 0
0 I 0 1 J 0 0
1 I 1 1 J 0 0
0 J 0 1 K 0 0
1 J 1 1 K 0 0
0 K 0 1 w 1 0
1 K 1 1 w 1 0

Try it online!

Wow, this is big.

u_ndefined

Posted 2017-05-16T20:35:37.283

Reputation: 1 253

Wow this is incredible! – MilkyWay90 – 2019-08-10T05:47:36.900

0

Emacs, 6 bytes

The cursor needs to be at the start of the line containing the string.

This will delete the entire line if there's no extension.

C-<SPC> C-e C-r . <RET> <BACKSPACE>

Explanation:

C-<SPC>      start a selection
C-e          go to the end of the line
C-r . <RET>  search for "." backward
<BACKSPACE>  delete the selected text (which should be the text before the last ".")

TuxCrafting

Posted 2017-05-16T20:35:37.283

Reputation: 4 547

0

Pushy, 13 bytes

K46-$v;F@46+"

Try it online!

               \ Implicit: string on stack as character codes
K46-           \ Subtract 46 from each code point, mapping '.' to 0
    $v;        \ While the top of stack is non-zero, move to auxiliary stack
       F       \ Copy auxiliary stack onto main stack
        @      \ Reverse (to obtain original order)
         46+   \ Add 46 (to obtain original characters)
            "  \ Print as a string.  

FlipTack

Posted 2017-05-16T20:35:37.283

Reputation: 13 242

0

Brain-Flak, 76 bytes

{((((([()()()]){}){}){}()){}{}<>)<>}<>{({}(((()()()()()){}()){}()){}<>)<>}<>

Try it online!

Explanation:

{          loop over stack
  (                            push
    (((([()()()]){}){}){}()){} -46
  {}                           plus the top of the stack
  <>)                          to the other side
<>}        retuen for more

<>      on the other side...

{       loop until 0
  (                             push
     {}                         the top of the stack
     (((()()()()()){}()){}()){} +46
  <>)                           to the first side
<>}       return for more

<> print the first side

6 bytes less than the other Brain-Flack solution.

MegaTom

Posted 2017-05-16T20:35:37.283

Reputation: 3 787

0

Perl 6, 11 bytes

{m/\.\w+$/}

Try it online!

bb94

Posted 2017-05-16T20:35:37.283

Reputation: 1 831

0

Befunge-98 (FBBI), 50 bytes

{v
 >~:a`!#v_
--2*86:$<:u-10_v#
02-u0}>:#,_@   >00

Try it online!

Puts string onto stack, then iterates through it in reverse, putting each new character onto new stack. Once a . is encountered, discard original stack and output new stack in 0gnirts format.

JPeroutek

Posted 2017-05-16T20:35:37.283

Reputation: 734

0

Forth (gforth), 45 bytes

: f begin 1 -1 d+ s" ."search 0= until type ;

Try it online!

Code Explanation

: f              \ start a new word definition
  begin          \ start an indefinite loop
    1 -1 d+      \ remove the first character from the string
    s" ."search  \ find the length and starting address of the first substring that starts with '.'
    0=           \ check if '.' was found in the string
  until          \ end the loop if not
  type           \ output the result
;                \ end the word definition

reffu

Posted 2017-05-16T20:35:37.283

Reputation: 1 361

0

33 v1.0, 13 bytes

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)

TheOnlyMrCat

Posted 2017-05-16T20:35:37.283

Reputation: 1 079

0

brainfuck, 45 bytes

,[>,]>+[[-]++[<->------]<---<[->+>+<<]>]>[.>]

Try it online!

Herman L

Posted 2017-05-16T20:35:37.283

Reputation: 3 611

-1

Python & JavaScript, 22 bytes

'x.h'.split('.').pop()

Explanation

I did split the string 'x.h', which is the full file name at the dot and then I did remove the last index in the list (the extension) and this happens to return the value of the removed list item which in my case would be the extension.

Note: This could run on either JavaScript or Python without adaptations

MmDeveloper

Posted 2017-05-16T20:35:37.283

Reputation: 1

4

Welcome to the site! A couple things: rather than hardcoding the x.h, you need to take it as input, as a parameter, or through another allowed input method. Also, this answer requires a read-evaluate-print loop (REPL) in order to work; this must be specified.

– Khuldraeseth na'Barya – 2018-03-13T00:38:59.110

1Welcome to the site! Unfortunately, this is only a snippet, and so is invalid. You can make it into a lambda like this: lambda x:x.split('.').pop(), or Python REPL like this: input().split('.').pop() (input format depends on whether you use Python 2 or Python 3). – Erik the Outgolfer – 2018-03-13T12:05:11.490