And*_*ech 35 javascript regex filenames
我需要一个正则表达式,可以删除文件名的扩展名,只返回文件的名称.
以下是输入和输出的一些示例:
myfile.png -> myfile
myfile.png.jpg -> myfile.png
Run Code Online (Sandbox Code Playgroud)
我显然可以手动执行此操作(即从最后一个点删除所有内容),但我确信有一个正则表达式可以自己执行此操作.
只是为了记录,我在JavaScript中这样做
Bol*_*wyn 83
只是为了完整性:如果没有正则表达式,如何实现这一目标?
var input = 'myfile.png';
var output = input.substr(0, input.lastIndexOf('.')) || input;
Run Code Online (Sandbox Code Playgroud)
在|| input需要的情况下,这里的护理lastIndexOf()提供-1.你看,它仍然是一个单行.
Amb*_*ber 40
/(.*)\.[^.]+$/
Run Code Online (Sandbox Code Playgroud)
结果将在第一个捕获组中.但是,在不使用正则表达式的情况下,找到最右边的位置然后将所有内容放在它之前可能更有效.
小智 11
/^(.+)(\.[^ .]+)?$/
Run Code Online (Sandbox Code Playgroud)
测试用例和其他失败的测试用例:
当然,上面的共同主题是"格式错误"的文件扩展名.但你总是要考虑那些极端情况.:P
测试失败的测试用例:
如何处理这些是有问题的,最好在特定项目的基础上决定.
匹配模式的正则表达式为:
/\.[^.]*$/
Run Code Online (Sandbox Code Playgroud)
它找到一个句点字符(\。),后跟0个或多个不是句点的字符([^。] *),然后是字符串的结尾($)。
/\.[^.]*$/
Run Code Online (Sandbox Code Playgroud)
/^(.+)(\.[^ .]+)?$/
Run Code Online (Sandbox Code Playgroud)
上面的模式是错误的-它也将始终包含扩展名。这是因为javascript regex引擎的工作方式。该(\.[^ .]+)标记是可选的,所以发动机将成功匹配整个字符串(.+)
http://cl.ly/image/3G1I3h3M2Q0M
这是我经过测试的regexp解决方案。
该模式将匹配路径中带有/不带有扩展名的filenameNoExt,同时考虑斜杠和反斜杠分隔符
var path = "c:\some.path/subfolder/file.ext"
var m = path.match(/([^:\\/]*?)(?:\.([^ :\\/.]*))?$/)
var fileName = (m === null)? "" : m[0]
var fileExt = (m === null)? "" : m[1]
Run Code Online (Sandbox Code Playgroud)
剖析以上模式:
([^:\\/]*?) // match any character, except slashes and colon, 0-or-more times,
// make the token non-greedy so that the regex engine
// will try to match the next token (the file extension)
// capture the file name token to subpattern \1
(?:\. // match the '.' but don't capture it
([^ :\\/.]*) // match file extension
// ensure that the last element of the path is matched by prohibiting slashes
// capture the file extension token to subpattern \2
)?$ // the whole file extension is optional
Run Code Online (Sandbox Code Playgroud)
http://cl.ly/image/3t3N413g3K09
http://www.gethifi.com/tools/regex
这将涵盖@RogerPate提到的所有情况,但也包括完整路径
| 归档时间: |
|
| 查看次数: |
61909 次 |
| 最近记录: |