eng.ahmed
eng.ahmed

Reputation: 925

Capture src value of an <img> tag with regex

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

Answers (4)

Abhishek Singh
Abhishek Singh

Reputation: 59

I face the same situation and I tried this and it worked for me.

(<img)[^/>]*(/>|>)

Here is the explanation:

Image for the explanation of above regex

This explanation is from the website https://extendsclass.com/regex-tester.html

Upvotes: 1

user557597
user557597

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

hwnd
hwnd

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

aleroot
aleroot

Reputation: 72636

You could simply use this expression to match an img tag as in the example :

<img([\w\W]+?)/>

Upvotes: 28

Related Questions