First, I would use the group()
method to retrieve the matched text, not toString()
. But it's probably just the URL part you want, so I would use parentheses to capture that part and call group(1)
retrieve it.
Second, I wouldn't assume src
was the first attribute in the <img>
tag. On SO, for example, it's usually preceded by a class
attribute. You want to add something to match intervening attributes, but make sure it can't match beyond the end of the tag. [^<>]+
will probably suffice.
Third, I would use something more restrictive than .*
to match the unknown part to the path. There's always a chance that you'll find two URLs on one line, like this:
<img src="http://so.com/foo.jpg"> blah <img src="http://so.com/bar.jpg">
In that case, the .*
in your regex would bridge the gap, giving you one match where you wanted two. Again, [^<>]*
will probably be restrictive enough.
There are several other potential problems as well. Are attribute values always enclosed in double-quotes, or could they be single-quoted, or not quoted at all? Will there be whitespace around the =
? Are element and attribute names always lowercase?
...and I could go on. As has been pointed out many, many times here on SO, regexes are not really the right tool for working with HTML. They can usually handle simple tasks like this one, but it's essential that you understand their limitations.
Here's my revised version of your regex (as a Java string literal):
"(?i)<img[^<>]+src\\s*=\\s*[\"']?(http://stackoverflow\\.com/[^<>]+\\.jpg)"