Javascript正则表达式匹配文件名和扩展名 [英] Javascript regex match filename with extension
问题描述
您好,我需要将文件名与扩展名匹配.
Hello i need to match filnames with extensions.
问题是路径可以是 unix 和 windows,所以用/或 \ 分隔,unix 也允许 .在文件名中,所以 t.est.txt 也应该匹配.
Problem is that paths could be both unix and windows, so seperated by / or \ also unix allows . in filenames, so t.est.txt also should be matched.
我的代码:
var regex = new RegExp('[\\/]?([/\w+.]+/\w+)/\s*$');
var value = this.attachment.fileInput.dom.value;
console.log(value.match(regex));
console.log(regex.exec(value));
这个正则表达式在 rubular 中运行良好.但是由于某种原因,即 chrome 和 firefox 不匹配任何字符串并返回 null.
this regex works fine in rubular. But for some reason ie, chrome and firefox does not match any string and returns null.
推荐答案
你可以只抓取最后一个 \
或 /
后面的任何内容,例如:
You could just grab whatever's at the end following the last \
or /
, such as:
var file = str.match(/[^\\/]+$/)[0];
(记住文件并不总是需要扩展名)
(Remember files don't always need extensions)
如果你真的想强制扩展匹配:
Though if you really want to force extension matching:
var file = str.match(/[^\\/]+\.[^\\/]+$/)[0];
这篇关于Javascript正则表达式匹配文件名和扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!