正则表达式:一次性获取没有扩展名的文件名? [英] Regex: Get Filename Without Extension in One Shot?
问题描述
我只想使用正则表达式获取文件名,所以我一直在尝试简单的事情,例如
I want to get just the filename using regex, so I've been trying simple things like
([^\.]*)
当然只有在文件名有一个扩展名时才有效.但如果是adfadsfads.blah.txt
,我只想要adfadsfads.blah
.我怎样才能用正则表达式做到这一点?
which of course work only if the filename has one extension. But if it is adfadsfads.blah.txt
I just want adfadsfads.blah
. How can I do this with regex?
关于大卫的问题,你为什么要使用正则表达式",答案是为了好玩".其实我用的代码很简单
In regards to David's question, 'why would you use regex' for this, the answer is, 'for fun.' In fact, the code I'm using is simple
length_of_ext = File.extname(filename).length
filename = filename[0,(filename.length-length_of_ext)]
但我喜欢尽可能学习正则表达式,因为它总是出现在 Geek 鸡尾酒会上.
but I like to learn regex whenever possible because it always comes up at Geek cocktail parties.
推荐答案
试试这个:
(.+?)(\.[^.]*$|$)
这将:
- 捕获以点开头的文件名(例如
.logs
是名为.logs
的文件,而不是文件扩展名),这在 Unix 中很常见. - 获取除最后一个点以外的所有内容:
foo.bar.jpeg
获取foo.bar
. - 处理没有点的文件:
secret-letter
为您提供secret-letter
.
- Capture filenames that start with a dot (e.g.
.logs
is a file named.logs
, not a file extension), which is common in Unix. - Gets everything but the last dot:
foo.bar.jpeg
gets youfoo.bar
. - Handles files with no dot:
secret-letter
gets yousecret-letter
.
注意:正如评论者 j_random_hacker 所建议的那样,这与宣传的一样,但出于可读性目的,您可能希望在前面加上锚点.
Note: as commenter j_random_hacker suggested, this performs as advertised, but you might want to precede things with an anchor for readability purposes.
这篇关于正则表达式:一次性获取没有扩展名的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!