简体   繁体   English

如何使用正则表达式从绝对路径中提取文件名

[英]How to extract a filename using regex from an absolute path

I am trying to extract just the filename from the following line: 我正在尝试从以下行中提取文件名:

"GET /mapitzend/public/components/font-awesome/css/font-awesome.css HTTP/1.1" 200 26651

In this case the expected result should be "font-awesome.css" I have gotten this far with my regex: 在这种情况下,预期的结果应该是“ font-awesome.css”。

\"(.[^\"]+)\s+HTTP

eith the regex above it returns: "GET /mapitzend/public/components/font-awesome/css/font-awesome.css HTTP 上面的正则表达式将返回:“ GET /mapitzend/public/components/font-awesome/css/font-awesome.css HTTP

What am I missing here.. 我在这里想念什么..

Try this regex: 试试这个正则表达式:

(?<=\\/)[^\\s\\/]*(?=\\s*HTTP)

Click for Demo 点击演示

Explanation: 说明:

  • (?<=\\/) - positive lookbehind to find the position immediately preceded by a / (?<=\\/) -向后寻找正号,以找到紧跟/的位置
  • [^\\s\\/]* - matches 0+ occurrences of any character which is neither a whitespace character nor a / [^\\s\\/]* -匹配0+次出现的既不是空格字符也不是/的任何字符
  • (?=\\s*HTTP) - Positive lookahead to match until the position which is immediately followed by 0+ whitespaces followed by HTTP . (?=\\s*HTTP) -要匹配的正向超前,直到位置紧跟着0+空格和HTTP

While extracting the file name using regex is possible, it's easier for start to extract the path using regex and then get the filename using basename() or pathinfo() : 虽然可以使用regex提取文件名,但是开始使用regex提取路径然后使用basename()pathinfo()获取文件名更容易:

$line = '"GET /mapitzend/public/components/font-awesome/css/font-awesome.css HTTP/1.1" 200 26651';

$m = array();
if (preg_match('/GET (.*) HTTP/', $line, $m)) {
    $filename = basename($m[1]);
}

Using only regex : 仅使用regex

if (preg_match('#GET /(.*/)*(.*) HTTP#', $line, $m)) {
    $filename = $m[2];
}

Using properties of a filename which has certain extension like .css , .html you can use following regex. 使用扩展名为.css.html的文件名的属性,可以使用以下正则表达式。

Regex: [^\\/]+?\\.[az]+ 正则表达式: [^\\/]+?\\.[az]+

Explanation: 说明:

[^\\/]+? matches a string whose preceding character was / . 匹配前一个字符为/的字符串。

\\.[az]+ matches the extension making sure it's a file. \\.[az]+与扩展名匹配,以确保它是文件。

Regex101 Demo Regex101演示

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

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