Jessica
Jessica

Reputation: 2435

Non-greedy regex match when searching from end

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?

Upvotes: 3

Views: 390

Answers (2)

Tom Belote
Tom Belote

Reputation: 590

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

http://(?!http://).*?\.png

Upvotes: 2

Smern
Smern

Reputation: 19076

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

Upvotes: 2

Related Questions