javascript Javascript正则表达式匹配文件名和扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19292210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:01:48  来源:igfitidea点击:

Javascript regex match filename with extension

javascriptregex

提问by kuldarim

Hello i need to match filnames with extensions.

您好,我需要将文件名与扩展名匹配。

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.

问题是路径可以是 unix 和 windows,所以用 / 或 \ 分隔,unix 也允许 . 在文件名中,所以 t.est.txt 也应该匹配。

My code :

我的代码:

var regex = new RegExp('[\/]?([/\w+.]+/\w+)/\s*$');
var value = this.attachment.fileInput.dom.value;
console.log(value.match(regex));
console.log(regex.exec(value));

this regex works fine in rubular. But for some reason ie, chrome and firefox does not match any string and returns null.

这个正则表达式在rubular 中工作正常。但出于某种原因,即 chrome 和 firefox 不匹配任何字符串并返回 null。

回答by VisioN

Try the following syntax:

尝试以下语法:

var filename = (value.match(/[^\/]+\.[^\/]+$/) || []).pop();

It should work fine for the following examples:

对于以下示例,它应该可以正常工作:

"path/to/file.ext"     --> "file.ext"
"path\to\file.ext"   --> "file.ext"
"path/to/file.ext.txt" --> "file.ext.txt"
"path/to/file"         --> ""

回答by SmokeyPHP

You could just grab whatever's at the end following the last \or /, such as:

您可以在最后一个\or之后抓取任何内容/,例如:

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

回答by Zathrus Writer

Credits go to RegeBuddy's library for this snippet:

此代码段的积分转到RegeBuddy的库:

if (/[^\\/:*?"<>|\r\n]+$/im.test(js)) {
    // Successful match
} else {
    // Match attempt failed
}