解压缩文件扩展名的Javascript正则表达式

解压缩文件扩展名的Javascript正则表达式

本文介绍了用于匹配/解压缩文件扩展名的Javascript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下正则表达式

var patt1=/[0-9a-z]+$/i;

提取字符串的文件扩展名,例如

extracts the file extension of strings such as

filename-jpg
filename#gif
filename.png

当string真的是一个带有一个点作为分隔符的文件名时,如何修改这个正则表达式只返回一个扩展名? (显然文件名#gif不是常规文件名)

How to modify this regular expression to only return an extension when string really is a filename with one dot as separator ? (Obviously filename#gif is not a regular filename)

UPDATE基于tvanofsson的评论我想澄清当JS函数收到字符串时,字符串将包含一个没有空格的文件名,没有圆点和其他特殊字符(它实际上将处理 slug )。问题不在于解析文件名,而在于错误地解析slugs - 当函数真正返回 null 或空字符串,这是需要纠正的行为。

UPDATE Based on tvanofsson's comments I would like to clarify that when the JS function receives the string, the string will already contain a filename without spaces without the dots and other special characters (it will actually be handled a slug). The problem was not in parsing filenames but in incorrectly parsing slugs - the function was returning an extension of "jpg" when it was given "filename-jpg" when it should really return null or empty string and it is this behaviour that needed to be corrected.

推荐答案

只需添加到正则表达式

var patt1=/\.[0-9a-z]+$/i;

因为点是正则表达式中的特殊字符,所以你需要将其转义为字面上匹配: \。

Because the dot is a special character in regex you need to escape it to match it literally: \..

您的模式现在将匹配任何以点结尾的字符串,后跟至少一个字符 [0-9a-z]

Your pattern will now match any string that ends with a dot followed by at least one character from [0-9a-z].

[
  "foobar.a",
  "foobar.txt",
  "foobar.foobar1234"
].forEach( t =>
  console.log(
    t.match(/\.[0-9a-z]+$/i)[0]
  )
)

如果你想将扩展名限制为一定数量的字符,还需要更换 +

if you want to limit the extension to a certain amount of characters also, than you need to replace the +

var patt1=/\.[0-9a-z]{1,5}$/i;

将允许点后至少1个,最多5个字符。

would allow at least 1 and at most 5 characters after the dot.

这篇关于用于匹配/解压缩文件扩展名的Javascript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:12