什么是文件扩展名?


10

您面临的挑战是找到提供的文件名的文件扩展名:

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

您必须从字符串的最后. 或最后.到结尾再获取文本。正则表达式的第一个捕获组匹配/\.([^.]+)$/有效,在.s 上分割输入并返回最后一个也是如此。

文件名将始终至少包含一个.,但可能包含多个.。(请参见示例)

输入将始终匹配^[.a-zA-Z0-9^!\[\]{}@$%+=]+$


17
在将挑战发布到主站点之前,请考虑将来使用沙盒以获取有关您挑战的反馈。
Mego

1
codegolf.meta.stackexchange.com/a/12432/59376-从您的挑战中得到了这个想法。
魔术章鱼缸

@carusocomputing不错的挑战!
程序员

1
为什么反对票?这个挑战是“微不足道的”吗?
亚伯汤姆

@AbelTom编辑历史表明,在该问题的第一稿中,不合格的原因是不赞成投票。
帕特里克·罗伯茨

Answers:



11

JavaScript(ES6),19个字节

没有文件扩展名时,返回完整文件名。我认为这是可以接受的未定义行为

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


未定义行为的要点是一切都会发生。虽然,鼻恶魔虽然仍未定义行为,但可能会使“没有恶意程序”子句失败。
约翰·德沃夏克

10

Mathematica,13 22字节

编辑:不确定我如何错过".bashrc"测试用例。感谢Artyer让我诚实。

FileExtension["a"<>#]&

如果输入匹配\.[^.]+,则FileExtension仅返回空字符串,因此我们在字母前面加上a。在任何其他情况下,前置a都不会影响的输出FileExtension


11
内置的Mathematica ...不足为奇。
程序员

1
如果没有任何可能的任何数学内建
函数,

我没有使用Mathematica的权限,但我怀疑这.ext不会导致任何结果,因为.bashrc需要输出而bashrc失败(在Mathics中失败)
Artyer


Mathematica只需要内置meta即可Create Built-in XXXXXXXX
魔术章鱼缸




7

c函数,21

  • 感谢@Dennis,节省了1个字节。
  • @JohanduToit节省了3个字节。
  • @Neil节省了2个字节。
  • @algmyr节省了1个字节。
f(s){s=rindex(s,46);}

在线尝试


1
如果可以使用传统的POSIX函数,则可以rindex用来保存字节。
algmyr

@algmyr当然,它可以在TIO上正常工作,所以我将使用它。我以前从未听说rindex()过-谢谢小费!
Digital Trauma

5

PHP,21字节

<?=pathinfo($argn,4);

在线尝试!

是以下的简短表达

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

路径信息

PHP,27字节

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

爆炸

在线尝试!

PHP <7.0,26字节

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

弃用的拆分


1
您是否在计算第一个尾随的换行符?它应该是27个字节,而不是28
康纳尔奥布莱恩

@ ConorO'Brien谢谢。我有无计数复制后从拆分版本``粘贴
约尔格Hülsermann

2
pathinfo()基于一个可能<?=pathinfo($argn,4);
manatwork '17


4

GNU Make,12个字节

$(suffix $1)

不使用内置的27个字节:

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

4

批处理,10个字节

@echo %~x1

一次就奇怪地竞争了。


4

V5,3个字节

由于此答案不可打印比可打印更多,因此这里是一个十六进制转储:

00000000: cd81 ae                                  ...

在线尝试!

这使用了Jan Dvorak的算法,它恰好是它的更有效的编码。

说明:

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

旧解决方案:

$T.d|


@EriktheOutgolfer完成
詹姆斯

等待®方式后跟一个点?大声笑,这很奇怪。
暴民埃里克(Erik the Outgolfer)'17年


3

果冻,4 字节

ṣ”.Ṫ

一个Monadic链接,使用文件名并返回扩展名而没有前导.

在线尝试!

怎么样?

从字面上看是做什么的...

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

3

,85个字节

去是...麻烦。

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

在线尝试!

代码中的括号示例:

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

2
()(){([])([()])}-它是有效的Brain-Flak吗?
eush77

5
@ eush77从技术上讲,它是有效的 Brain-Flak,因为它可以正常运行,但是却没有任何有趣/有用的作用。它要么是2没有指令/命令的文字,要么是任何东西,或者是无限循环,根据输入不断分配更多的内存。
詹姆斯

使用filepath.Ext将为您节省一些时间
鲍威尔(Powelles)

3

JavaScript(ES6),33 31 28字节

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

注释中的规范更改消除了对 +1

-3个字节感谢nderscore


1
-3 slice和模板字符串执行:s=>s.slice(s.lastIndexOf`.`)
nderscore

3

Common Lisp,57个字节

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

在线尝试(添加了一些字节来调用此匿名函数并显示返回的字符串)

说明

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

我得到反向字符串的子字符串,从0开始,在此结束


3

Gema,3个字符

*.=

样品运行:

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

3

MATL,8个 7字节

46&YbO)

MATL Online上尝试一下!

说明

        % 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


3

C#,33 41个字节

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

根据建议编辑:

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

1
您需要将using Sytem.Linq;字节数包括在内
TheLethalCoder

而且a=>a.Split('.').Last();隐式返回的时间也更短
TheLethalCoder

@TheLethalCoder感谢您提供建议的修复程序,此方法仍然很新:)
LiefdeWen

我感到惊讶的是,这比我使用的解决方案还要长Path...
TheLethalCoder

3

AWK,14个 13个字符

10个 9个字符的代码+ 4个字符的命令行选项。)

{$0=$NF}1

谢谢:

样品运行:

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

您不需要;。而且仅供参考,awk '{$0=$NF}1 可以工作,不需要命令行选项。哦,我一定累了。我看你在那做什么。您确实需要命令行选项。
罗伯特·本森

1
谢谢@RobertBenson。我不知道为什么把它放在;那里。
manatwork


3

Java 8,52 27字节

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

在这里尝试。

将最后一个点之前的所有内容(以及该点本身)全部替换为空。

这比使用split(s->s.split("\\.")[s.split("\\.").length-1];)或substring(s->s.substring(s.lastIndexOf('.'));)短。


3

出租车,1397字节

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.

在线尝试!

出租车没有倒车功能,因此迅速膨胀。逻辑是:

  1. 将字符串分成字符
  2. 反转数组
  3. 遍历每个对象,直到找到一个周期,然后将每个对象存储在FIFO数组中
  4. 清空阵列(因为只有一个LIFO阵列可用)
  5. 将FIFO阵列转储到LIFO阵列中
  6. 连接LIFO数组并输出

3

Vim,5个字节

$F.d0

说明:找到最后 .一行,删除之前的所有内容

另一种更长,但在我看来仍然很有趣的9字节方法(请注意结尾处的新行)

d/.*\./e

这个工作原理类似,为5个字节(再次在行尾添加):

d?\.


2

Brain-Flak,84个字节

包括+2 -rc

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

在线尝试!

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

2

Japt6 5字节

q'. o

在线尝试!

说明

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

当您只需要返回数组的最后一项时,可以使用o代替gJ。(从@obarakon那里学到了这个技巧)
-ETHproductions

2

jq,15个 14个字符

11个10个字符的代码+ 4个字符的命令行选项。)

./"."|last

样品运行:

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

在线测试


2

八度,24字节

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

创建一个匿名函数ans,该函数可以接受字符串作为输入

在线演示

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.