繁体   English   中英

正则表达式从URL中提取没有扩展名的文件名

[英]Regular expression to extract filename without an extension from a url

我有这两个不同的网址

https://www.examplecom/dir/dir1/filename
https://www.example.com/dir/dir1/filename?start=83477&index=2

并且想要在不使用lookbehind正则表达式的情况下提取filename ,因为我打算在JSON脚本中使用它。

/[^/]*$/是我到目前为止,但它只适用于第一个网址。

你可以用

s.match(/([^\/?#]+)(?:[?#].*)?$/)[1]

请参阅正则表达式演示 它将支持文件名跟随的情况? #或字符串结尾。

细节

  • ([^\\/?#]+) - 第1组捕获除/之外的1个或多个字符, ? #
  • (?:[?#].*)? - 一个可选的序列? 或者#跟随任何0+字符尽可能多
  • $ - 结束字符串。

JS演示:

 var strs = ['https://www.examplecom/dir/dir1/filename', 'https://www.example.com/dir/dir1/filename?start=83477&index=2', 'https://www.example.com/dir/dir1/filename#index', 'https://www.examplecom/dir/']; var rx = /([^\\/?#]+)(?:[?#].*)?$/; for (var s of strs) { var m = s.match(rx); if (m) { console.log(s, "=>", m[1]); } else { console.log(s, "=> No match!"); } } 

因为它是一个url ,你可能想要使用URL及其pathname ,然后简单地split()它, reverse()数组并获取第一个项[0]

 const url1 = new URL('https://www.example.com/dir/dir1/filename'); const url2 = new URL('https://www.example.com/dir/dir1/filename?start=83477&index=2'); console.log(url1.pathname.split("/").reverse()[0]); console.log(url2.pathname.split("/").reverse()[0]); 


或者使用pop()

 const url1 = new URL('https://www.example.com/dir/dir1/filename'); const url2 = new URL('https://www.example.com/dir/dir1/filename?start=83477&index=2'); console.log(url1.pathname.split("/").pop()); console.log(url2.pathname.split("/").pop()); 

也许是这样的:

 var urls=[ 'https://www.examplecom/dir/dir1/filename', //only file name 'https://www.example.com/dir/dir1/filename?start=83477&index=2', //with get params 'https://www.example.com/dir/dir1/filename.php?start=83477&index=2' //with extension ]; for(var key in urls){ var url= urls[key]; var file_name_no_ext= url.replace(/\\?.*$/,"").replace(/.*\\//,"").replace(/\\.[^/.]+$/, ""); console.log(file_name_no_ext); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM