Regex从文件中提取路径



我正在尝试构建一个regexp或字符串拆分/替换,它将使用以下测试返回文件路径

let filepath_1 = "./path/to/file.js";     // ./path/to/
let filepath_2 = "./path/to/file.min.js"; // ./path/to/
let filepath_3 = "./path/to/";            // ./path/to/
let filepath_4 = "./path/to";             // ./path/to
let filepath_5 = "/path/to";              // /path/to
let filepath_6 = "path/to";               // path/to 

最终结果中的斜杠其实并不重要,只要文件从结果中消失,并且它不认为to是文件名。。

到目前为止,我最大的努力是使用file.replace(/[^/]*$/, ""),但它将删除/path/to中的to。我需要一些关于"字符

答案如下:

https://regex101.com/r/XPalNK/2

将此模式替换为空字符串。

(!?[w-]+..*)

Regex在这种情况下可能不会产生最可读的解决方案,因为隐式存在if/then。一个简单的split怎么样?

p = ["./path/to/file.js", "./path/to/file.min.js", "./path/to/", "./path/to", "/path/to", "path/to"]
output = p.map(s => {
// Begin
a = s.split("/")
if (a[a.length - 1].includes(".")) {
a.pop()
return a.join("/") + "/"
}
return a.join("/")
// End
})
console.log("output", output)

您可以使用以下内容来替换基于上述示例不需要的内容(即,如果您只需要删除路径末尾的文件名(:

.replace(/[^/]+.w+$/, '')

请参阅regex演示。正则表达式将匹配以下字符以外的一个或多个字符一个/(具有[^/]+(,然后是.(具有.(,然后在字符串末尾的任何一个或多个字字符(w+(($(。

您可以使用以下方法提取您需要的内容:

/^(?:.*/)?[^/]+/[^/]+/?/

请参阅regex演示。详细信息:

  • ^-字符串的开头
  • (?:.*/)?-零个或多个.字符的可选序列,后跟/
  • [^/]+-除/之外的零个或多个字符
  • /-一个/字符
  • [^/]+-除/之外的零个或多个字符
  • /?-可选的/字符

查看JavaScript演示:

let filepath_1 = "./path/to/file.js";     // ./path/to/
let filepath_2 = "./path/to/file.min.js"; // ./path/to/
let filepath_3 = "./path/to/";            // ./path/to/
let filepath_4 = "./path/to";             // ./path/to
let filepath_5 = "/path/to";              // /path/to
let filepath_6 = "path/to";               // path/to 
const arr = [filepath_1, filepath_2, filepath_3, filepath_4, filepath_5, filepath_6];
// Replacing
const reg = /[^/]+.w+$/;
arr.forEach( x => console.log(x, "=>", x.replace(reg, '')) )
// Matching
const regex = /^(?:.*/)?[^/]+/[^/]+/?/g;
arr.forEach( x => console.log(x, "=>", x.match(regex)?.[0]) )

最新更新