Reputation: 925
I want to grab an img
tag from text returned from JSON data like that. I want to grab this from a string:
<img class="img" src="https://fbcdn-photos-c-a.akamaihd.net/hphotos-ak-frc3/1239478_598075296936250_1910331324_s.jpg" alt="" />
What is the regular expression I must use to match it?
I used the following, but it is not working.
"<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"
Upvotes: 26
Views: 63155
Reputation: 59
I face the same situation and I tried this and it worked for me.
(<img)[^/>]*(/>|>)
Here is the explanation:
This explanation is from the website https://extendsclass.com/regex-tester.html
Upvotes: 1
Reputation:
Your regex doesn't match the string, because it's missing the closing /
.
Edit - No, the /
is not necessary, so your regex should have worked. But you can relax it a bit like below.
Slightly modified:
<img\s[^>]*?src\s*=\s*['\"]([^'\"]*?)['\"][^>]*?>
Upvotes: 21
Reputation: 70722
Please note you shouldn't use regular expressions to parse HTML for the various reasons
<img\s+[^>]*src="([^"]*)"[^>]*>
Or use Jsoup
...
String html = "<img class=\"img\" src=\"https://fbcdn-photos-c-a.akamaihd.net/
hphotos-ak-frc3/1239478_598075296936250_1910331324_s.jpg\" alt=\"\" />";
Document doc = Jsoup.parse(html);
Element img = doc.select("img").first();
String src = img.attr("src");
System.out.println(src);
Upvotes: 10
Reputation: 72636
You could simply use this expression to match an img tag as in the example :
<img([\w\W]+?)/>
Upvotes: 28