正则表达式帮助从路径获取文件名时需要

时间:2014-01-10 13:31:38

标签: regex path cq5

我有以下要求 我有格式的网址

/content/any-site-name(alphanumeric)/filename.css

它始终以/content开头,目录可以是任何内容,可以是任何深度目录。文件扩展名始终为.css

需要编写正则表达式以从输入的路径中获取以下路径

/content/sitename/filename.css

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式:

/content(/[a-zA-Z0-9]+)*/[a-zA-Z0-9]+[.]css

Regular expression in details

答案 1 :(得分:0)

如果你想试试这个:

/content/folder1/folder2/sitename/filename.css 

到此:

/content/sitename/filename.css

并假设实际单词“content”永远不会改变,您可以尝试:

/\/content(\/[A-Za-z0-9]+)(?:[\/][^.]*)*([\/][a-zA-Z0-9]+.css)/    

匹配结果为$ 1:“/ sitename”,$ 2:“/ filename.css”然后获得所需的字符串,只需添加所需的部分: mystring =“/ content”+ $ 1 + $ 2

答案 2 :(得分:0)

如果我不满意,这就是你要找的东西:

/\/content\/mysite\/(?:[\w-]+\/)*([\w-]+\.css)/

适用于:

  • /content/mysite/filename.css
  • /content/mysite/folder1/filename.css
  • /content/mysite/folder1/folder2/filename.css
  • /content/mysite/folder1/folder2/folder3/filename.css
  • 等......

enter image description here

Test this regex online

示例应用程序():

function getShortPath($url) {
    return preg_replace('/\/content\/mysite\/(?:[\w-]+\/)*([\w-]+\.css)/', '/content/mysite/$1', $url);
}

echo getShortPath('/content/mysite/filename.css').'<br>';
echo getShortPath('/content/mysite/folder1/filename.css').'<br>';
echo getShortPath('/content/mysite/folder1/folder2/filename.css').'<br>';
echo getShortPath('/content/mysite/folder1/folder2/folder3/filename.css').'<br>';
/*
/content/mysite/filename.css
/content/mysite/filename.css
/content/mysite/filename.css
/content/mysite/filename.css
*/

注意:您可以通过命名捕获组来改进此正则表达式:

/\/content\/(?<sitename>[\w-]+)(?<path>\/(?:[\w-]+\/)*)(?<filename>[\w-]+\.css)/

然后你会得到结果:

  • /content/mysite/filename.css
    { sitename: "mysite", path: "/", filename: "filename.css" }
  • /content/mysite/folder1/folder2/filename.css
    { sitename: "mysite", path: "/folder1/folder2/", filename: "filename.css" }

Test this regex online