Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将URL最后一部分与JavaScript匹配的正则表达式_Javascript_Regex - Fatal编程技术网

将URL最后一部分与JavaScript匹配的正则表达式

将URL最后一部分与JavaScript匹配的正则表达式,javascript,regex,Javascript,Regex,我有一些url,我喜欢捕捉url的最后一部分 我的URL是以 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 我最喜欢的是郁金香 我试过了,但运气不

我有一些url,我喜欢捕捉url的最后一部分

我的URL是以

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
我最喜欢的是郁金香

我试过了,但运气不好

\/.*(-\d+x\d+)\.(jp(e)?g|png|gif)

还有更好的主意吗

看看
lastIndexOf
方法:

var index = url.lastIndexOf("/");
var fileName = url.substr(index)
*/(.*)
使用此模式并获得组1。我想它会起作用。

*
是一个贪婪的正则表达式,因此它将一直匹配到最后一个斜杠。之后,组1中的最后一个字符(您需要的)

以下正则表达式将起作用:

/[^\/]+$/
使用此正则表达式:-

^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$

如果您确定所有图像都是jpg,请使用
$6

获取文件名:

/.\/\S+\.jpg/
否则,更一般的情况是:

/.\/\S+\.\w{2,3}/
即:

. 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

如果您需要大量的ULR操作,并且希望您的代码更具可读性,我建议使用优秀的uri.js,这比上面所有的都好。请注意,如果url有参数,此解决方案不起作用。i、 例如:www.something.com/image.jpg?size=100x100(因为这仍然是一个很好的解决方案),请参阅一个处理更复杂URI(URI.js)的漂亮库。我认为@winSharp93的答案是最好的。这也会提取查询字符串。