正则表达式将 URL 最后一部分与 JavaScript 匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9495322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to match the URL last part with JavaScript
提问by Merianos Nikos
I have some URLs and I like to catch the final part of the url.
我有一些网址,我喜欢捕捉网址的最后一部分。
My URLs are in the form of
我的网址是
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips-150x200.jpg
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips-500x350.jpg
and what I like to catch is the /Tulips.......jpg
我喜欢捕捉的是/郁金香.......jpg
I have try that but with no luck
我试过了,但没有运气
\/.*(-\d+x\d+)\.(jp(e)?g|png|gif)
Any better idea?
有什么更好的主意吗?
回答by Matthias
Take a look at the lastIndexOf
method:
看一下lastIndexOf
方法:
var index = url.lastIndexOf("/");
var fileName = url.substr(index)
回答by Alan Haggai Alavi
The following regular expression will work:
以下正则表达式将起作用:
/[^\/]+$/
回答by Siva Charan
Use this Regex:-
使用这个正则表达式:-
^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$
Get file name using $6
使用获取文件名 $6
回答by Alberto De Caro
If you are sure that all the images are jpg:
如果您确定所有图像都是 jpg:
/.\/\S+\.jpg/
Otherwise, more generale:
否则,更一般:
/.\/\S+\.\w{2,3}/
That is:
那是:
. any char
\/ the slash before the file name
\S+ any non blank char to match the file name (at least one)
\. the file extension separator
jpg or \w{3,4} the file extension
回答by shift66
.*/(.*)
use this pattern and get the group 1.it will work I guess..*
is a greedy regex so it will match until the lastslash. After that in group 1 will be the last characters (what you need)
.*/(.*)
使用这种模式并获得第 1 组。我猜它会起作用。.*
是一个贪婪的正则表达式,所以它会匹配到最后一个斜杠。之后,第 1 组将是最后一个字符(您需要什么)