【问题标题】:Regular expression to extract filename without an extension from a url用于从 url 中提取不带扩展名的文件名的正则表达式
【发布时间】:2018-12-29 05:24:25
【问题描述】:

我有这两个不同的网址

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

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

/[^/]*$/ 是我目前所拥有的,但它只适用于第一个 url。

【问题讨论】:

  • 或更好.*\/([\w.]+) > [1]
  • @bobblebubble 想知道这对于像 file-name 或 url 编码版本 file%2dname 这样的文件名是如何工作的
  • 我喜欢s.match(/.*\/([^?]*)[?]?/)
  • @MarkMeyer 使用 [^?]+ 而不是 [\w.]+ 但是 [?]? 呢? (:

标签: javascript json regex


【解决方案1】:

你可以使用

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

请参阅regex demo。它将支持文件名后跟?# 或字符串结尾的情况。

详情

  • ([^\/?#]+) - 第 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!");
  }
}

【讨论】:

    【解决方案2】:

    因为它是一个 url,你可能想要使用URL 和它的pathname,然后简单地使用split() 它,reverse() 数组并获取第一项@ 987654325@.

    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());

    【讨论】:

      【解决方案3】:

      可能是这样的:

      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);
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-19
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        • 1970-01-01
        • 2011-04-09
        • 2013-03-18
        相关资源
        最近更新 更多