您好,我需要将文件名与扩展名进行匹配。
问题在于路径可能同时是unix和windows,因此用/或\分隔也是unix allow。在文件名中,因此t.est.txt也应该匹配。
我的代码:
var regex = new RegExp('[\\/]?([/\w+.]+/\w+)/\s*$');
var value = this.attachment.fileInput.dom.value;
console.log(value.match(regex));
console.log(regex.exec(value));
Run Code Online (Sandbox Code Playgroud)
这种正则表达式在rubular中可以正常工作。但是由于某种原因,即chrome和firefox不匹配任何字符串,并返回null。
尝试以下语法:
var filename = (value.match(/[^\\/]+\.[^\\/]+$/) || []).pop();
Run Code Online (Sandbox Code Playgroud)
适用于以下示例:
"path/to/file.ext" --> "file.ext"
"path\\to\\file.ext" --> "file.ext"
"path/to/file.ext.txt" --> "file.ext.txt"
"path/to/file" --> ""
Run Code Online (Sandbox Code Playgroud)
您只需抓住最后一个\或之后的末尾内容/,例如:
var file = str.match(/[^\\/]+$/)[0];
Run Code Online (Sandbox Code Playgroud)
(记住文件并不总是需要扩展名)
但是,如果您真的想强制扩展匹配:
var file = str.match(/[^\\/]+\.[^\\/]+$/)[0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11783 次 |
| 最近记录: |