TransWikia.com

What's the file extension?

Code Golf Asked by programmer5000 on January 15, 2021

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

92 Answers

Keg, -hd, 4 bytes

./÷

Try it online!

Splits on dots, and prints the last element.

Answered by Lyxal on January 15, 2021

Pip, 10 bytes

@RV(q^".")

Splits on dots, gets first element of reverse. I wish I could make this work without the parentheses.

Try it online!

Answered by Razetime on January 15, 2021

8086 Assembly (NASM) + DOS, 262 bytes source, 50 bytes assembled

I'm pretty new to assembly, but I thought I'd give this a try. This is a full DOS program, not just a snippet.

section .bss
b resb 256
org 256
section .text
mov byte[b],254
mov ah,10
mov dx,b
int 33
mov bh,0
mov bl,[b+1]
add bx,b+2
mov bp,bx
l:sub bx,1
cmp byte[bx],46
jne l
mov byte[bx],10
p:mov ah,2
mov dl,[bx]
int 33
add bx,1
cmp bx,bp
jb p
int 32

Essentially, it reads a line of text into a buffer, seeks the end, then seeks backwards until it reaches a .. Then it just prints the rest of the string from that point on. I wasn't able to use DOS's built-in print function, though, since that uses $ as the end-of-string character, which the prompt says is a valid character for the extension itself.

Here is the hexdump of the assembled binary:

00000000  c6 06 34 01 fe 88 e4 ba  34 01 cd 21 b7 00 8a 1e
00000010  35 01 81 c3 36 01 89 dd  83 eb 01 80 3f 2e 75 f8
00000020  c6 07 0a b4 02 8a 17 cd  21 83 c3 01 39 eb 72 f3
00000030  cd 20

Answered by gary600 on January 15, 2021

Python3 (32 bytes)

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

Try it online!

Answered by Ryan Rudes on January 15, 2021

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!

Answered by Razetime on January 15, 2021

Arn, 6 bytes

Ê^!⁺╔d

Try it!

Explained

Unpacked: :!".":}

    _ Variable initialized to STDIN; implied
  :! Split on
    "." String containing a period
:} Tail

Answered by ZippyMagician on January 15, 2021

Setanta, 66 34 bytes

gniomh(s){toradh roinn@s(".")[-1]}

Try it here!

Answered by bb94 on January 15, 2021

brainfuck, 45 bytes

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

Try it online!

Answered by Herman L on January 15, 2021

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)

Answered by TheOnlyMrCat on January 15, 2021

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
 

Answered by reffu on January 15, 2021

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.

Answered by JPeroutek on January 15, 2021

Perl 6, 11 bytes

{m/.w+$/}

Try it online!

Answered by bb94 on January 15, 2021

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.

Answered by MegaTom on January 15, 2021

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.

Answered by u-ndefined on January 15, 2021

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.  

Answered by FlipTack on January 15, 2021

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

Answered by TuxCrafting on January 15, 2021

Pepe, 48 bytes

rEeeEeEEEeREEeREEEerEEREEEEEEEreererEEEEeEeereee

Try it online!

Answered by u-ndefined on January 15, 2021

Red 9 bytes

Suffix? f

Assumes file is is in word 'f

Answered by AngryCutlery on January 15, 2021

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

? [email protected][]h
.h0wC[]h

Answered by wooshinyobject on January 15, 2021

R, 40 26 bytes

-14 bytes thanks to J.Doe

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

Try it online!

Answered by Robert S. on January 15, 2021

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

Answered by Gabriel Mills on January 15, 2021

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
    "[email protected][]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

Answered by HatsuPointerKun on January 15, 2021

V, 4 bytes

òdt.

Try it online!

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

Answered by oktupol on January 15, 2021

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("[email protected][]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

Answered by jrtapsell on January 15, 2021

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("[email protected][]h", "h0wC[]h"),
        Test("agent.000", "000")
)

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

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

Answered by jrtapsell on January 15, 2021

Funky, 26 bytes

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

Try it online!

Answered by ATaco on January 15, 2021

SmileBASIC, 45 bytes

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

Outputs extension with the period.

Answered by 12Me21 on January 15, 2021

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

Answered by Engineer Toast on January 15, 2021

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.

Answered by rafa11111 on January 15, 2021

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.

Answered by Giuseppe on January 15, 2021

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

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

Implicit using System.Linq; FTW!

Try it online!

Answered by Pavel on January 15, 2021

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

Answered by sirtomato999 on January 15, 2021

T-SQL, 48 bytes

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

SQL Fiddle

Answered by Razvan Socol on January 15, 2021

Stax, 4 bytes

'./H

Run and debug online!

Explanation

Split on ., take last part.

Answered by Weijun Zhou on January 15, 2021

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

Answered by Jo King on January 15, 2021

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.

Answered by Tarryk Ttmm on January 15, 2021

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

Answered by drham on January 15, 2021

Add++, 9 bytes

L,"."$tbU

Try it online!

Answered by caird coinheringaahing on January 15, 2021

CJam, 6 bytes

q'./W=

Try it online!

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

Answered by Esolanging Fruit on January 15, 2021

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

Answered by Jhynjhiruu Rekrap on January 15, 2021

><>, 50 bytes

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

Try it online!

Answered by hakr14 on January 15, 2021

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?.

Answered by oktupol on January 15, 2021

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

Answered by Taylor Scott on January 15, 2021

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!

Answered by Taylor Scott on January 15, 2021

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

Answered by Taylor Scott on January 15, 2021

Excel, 58 bytes

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

Answered by Wernisch on January 15, 2021

Perl 5, 8 bytes

7 bytes code + 1 for -p.

s;.*.;

Try it online!

Answered by Dom Hastings on January 15, 2021

Ohm v2, 5 bytes

I..ï⁾

Try it online!

Answered by Cinaski on January 15, 2021

K (oK), 6 bytes

Solution:

*|"."

Try it online!

Examples:

*|".""whats.up.txt"
"txt"
  *|".""[email protected][]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

Answered by streetster on January 15, 2021

Ruby, 16 bytes

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

Try it online!

Answered by daniero on January 15, 2021

Julia, 22 bytes

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

Answered by EricShermanCS on January 15, 2021

Tcl, 21 bytes

puts [file ext $argv]

Try it online!

Answered by sergiol on January 15, 2021

Cheddar, 16 bytes

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

simple regex solution. Alternative solution using split:

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

Answered by Downgoat on January 15, 2021

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;
}

Answered by pizzapants184 on January 15, 2021

Haskell, 32 30 29 bytes

-1 byte thanks to Laikoni

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

self-explanatory

Answered by Julian Wolf on January 15, 2021

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!

Answered by Felipe Nardi Batista on January 15, 2021

C#, 35 bytes

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

Try it online!

Answered by TheLethalCoder on January 15, 2021

REXX 53

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

Answered by theblitz on January 15, 2021

Pyth, 5 bytes

ecz.

try it here

Answered by Erik the Outgolfer on January 15, 2021

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.txtncarrot.memenlolnwhat..is..this..filen.bashrcnT00M@n3KaPZ.h0wC[]h'
txt
meme
lol
file
bashrc
h0wC[]h

Answered by manatwork on January 15, 2021

C#, 47 34 27 bytes

System.IO.Path.GetExtension

Saved 6 bytes thanks to @totallyhuman.

Try it online!

Answered by TheLethalCoder on January 15, 2021

Octave, 24 bytes

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

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

Online Demo

Answered by Suever on January 15, 2021

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

Answered by Suever on January 15, 2021

Gema, 3 characters

*.=

Sample run:

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

Answered by manatwork on January 15, 2021

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

Answered by manatwork on January 15, 2021

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('.'));).

Answered by Kevin Cruijssen on January 15, 2021

Batch, 10 bytes

@echo %~x1

Strangely competitive for once.

Answered by Neil on January 15, 2021

GNU Make, 12 bytes

$(suffix $1)

Not using a builtin, 27 bytes:

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

Answered by eush77 on January 15, 2021

C#, 33 41 bytes

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

Edit as suggested:

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

Answered by LiefdeWen on January 15, 2021

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

Answered by ASCII-only on January 15, 2021

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

Answered by user65167 on January 15, 2021

Javascript (ES5), 38 bytes

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

Answered by Sinned on January 15, 2021

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.

Answered by Digital Trauma on January 15, 2021

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!

Answered by Oliver on January 15, 2021

Japt, 6 5 bytes

q'. o

Try it online!

Explanation

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

Answered by Luke on January 15, 2021

Ruby, 21 bytes

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

12 bytes

File.extname

Answered by marmeladze on January 15, 2021

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("[email protected][]h")) // -> h0wC[]h
console.log(f(".bashrc")) // -> bashrc

Answered by Arnauld on January 15, 2021

Groovy, 37 bytes

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

Answered by Magic Octopus Urn on January 15, 2021

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.

Answered by ngenisis on January 15, 2021

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:

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

Answered by totallyhuman on January 15, 2021

Pure bash, 13

echo ${1##*.}

Try it online.

Answered by Digital Trauma on January 15, 2021

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

Answered by Riley on January 15, 2021

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

Answered by programmer5000 on January 15, 2021

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|

Answered by James on January 15, 2021

Retina, 5 bytes

.*.

Replaces everything and a dot with nothing at all.

Try it online!

Answered by John Dvorak on January 15, 2021

Python 2, 25 bytes

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

Try it online!

Answered by totallyhuman on January 15, 2021

sed, 8 bytes

s:.*.::

Try it online!

Answered by eush77 on January 15, 2021

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

Answered by Jörg Hülsermann on January 15, 2021

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)

Answered by Jonathan Allan on January 15, 2021

05AB1E, 4 bytes

'.¡¤

Try it online! or Try All Tests

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

Answered by Riley on January 15, 2021

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

Answered by Stephen on January 15, 2021

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]

Answered by programmer5000 on January 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP