Question

I read that you should use ? to match text non-greedily, so the regex

http://.*?\.png

...used on

http://example.png.png

...would return http://example.png.

But the non-greediness only seems to work from left to right. That is, if I matched it on

http://http://example.png

...it would return http://http://example.png.

How can I get the code to match http://example.png only?

Was it helpful?

Solution

Try this:

http://[A-Za-z0-9_-]+\.png

It wont get the first http:// because it has more than [A-Za-z0-9_-]+ between it and .png

Could also use this if you are worried about other characters in the URL:

http://[^:]+?\.png

OTHER TIPS

You could use a negative look ahead too, but I think smerny 's answer is better.

http://(?!http://).*?\.png
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top