正则表达式匹配URL末尾的文件名 [英] Regex to match filename at end of URL
问题描述
有这样的文字:
http://img.oo.com.au/prod/CRWWBGFWG/1t44.jpg
和其他文本一样,最后 1
可以是任何其他号码,最后一个 44
也可以是任何其他号码,我需要一个匹配 /1t44.jpg
。到目前为止我尝试的所有内容( /.+?\。([^ \。] +)$
)匹配第一个斜杠( // img.oo.com.au/prod/CRWWBGFWG/1t44.jpg
)。
And other texts like this where the last 1
can be any other number and the last 44
can be any other number as well, I need a regex that will match /1t44.jpg
. Everything I've tried so far (/.+?\.([^\.]+)$
) matches from the first slash (//img.oo.com.au/prod/CRWWBGFWG/1t44.jpg
).
我正在使用javascript所以无论如何工作在 RegexPal 上应该这样做。
I'm using javascript so whatever works on RegexPal should do.
提前致谢。
推荐答案
如果要将文件名与非常特定的文件扩展名匹配,可以使用以下内容:
If you want to match a filename with a very specific file extenstion, you can use something like this:
/\/\dt\d\d\.jpg$/
匹配:
a slash
followed by a digit
followed by the letter 't'
followed by two digits
followed by '.jpg' at the end of the string
或者,如果你真的只想要文件名(无论是在带有任何文件扩展名的最后一个斜杠之后),那么你可以使用它:
Or, if you really just want the filename (whatever is after the last slash with any file extension), then you can use this:
/\/[^\/]+$/
匹配:
a slash
followed by one or more non-slash characters
at the end of the string
在您的示例字符串中 http://img.oo.com.au/prod/CRWWBGFWG/1t44.jpg
,两者都匹配 /1t44.jpg
。第一个显然更具限制性,因为它需要特定的文件名格式。第二个匹配任何文件名。
In your sample string of http://img.oo.com.au/prod/CRWWBGFWG/1t44.jpg
, both of these will match /1t44.jpg
. The first is obviously much more restrictive since it requires a specific format of the filename. The second matches any filename.
其他选择。在node.js开发中,您可以使用 路径
模块并使用 path.parse()
来打破其所有各种组件的路径。
Other choices. In node.js development, you can use the path
module and use path.parse()
to break a path up into all of its various components.
并且,为浏览器编写了各种库,这些库也将分解其组件的路径。
And, there are various libraries written for the browser that will break up a path into its components too.
这篇关于正则表达式匹配URL末尾的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!