Click here to Skip to main content
15,941,828 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want a regex that i want to get the src value from the image tag

for example

<img title="abc" src="folder/MyImage.jpeg" alt="">

i want "folder/MyImage.jpeg"

How can i achieve using regex ???

This is the expression you need: <img[^>]*?src=(['"])(.*?)\1.*?>. See linqpad sample:
string pattern = @"<img[^>]*?src=(['""])(.*?)\1.*?>";
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline;
string text = @"<a href=""/hireso/567-lexikon-aprilisi-nepi-joslatok"" class=""thumbnail"">
        <img src='' />
<p>Újra eltelt a egy hónap, és az időjárással kapcsolatos népi megfigyelések áprilisi állomásához érkeztünk.</p>
<h4><a href='/hireso/536-lexikon-idojarasi-rekordok-a-vilagban'>Lexikon: időjárási rekordok a világban</a></h4>
<a href=""/hireso/536-lexikon-idojarasi-rekordok-a-vilagban"" class=""thumbnail"">
        <img src="""" />
<p>Meteorológiai szélsőségekről szóló cikksorozatunk utolsó részéhez érkeztünk, amiben a világ rekordokról olvashatsz. Az előző cikkekben (1, 2) is voltak jócskán meglepő adatok, hát még a most következőben!</p>";

Regex re = new Regex(pattern, options);
var srcs = re.Matches(text).Cast<Match>().Select(x => x.Groups[2].Value);

This last Dump() is a LinqPad thing, but the srcs varaible will hold a list of string with the src values from the img tags.
Share this answer
Kenneth Haugland 4-Apr-13 13:44pm    
That would also work. 5ed
fjdiewornncalwe 4-Apr-13 14:02pm    

Have a look here:[^]


But now I found that you can't parse HTML using a regular expression:[^]

To parse HTML, have a look at this article:
Parsing HTML Tags in C#[^]

You can also use the HtmlAgilityPack:[^]
Share this answer
[no name] 4-Apr-13 13:05pm    
This expression help me if i've one image tag... if more than one tag then it is not working it just find the first src....
what i need to do can you help me????
Thomas Daniels 4-Apr-13 13:19pm    
I updated my answer.
Well, it depends what you want to do, but I would use Balanced grouping with the start condition "<img" and the end condition ">"

For details on how to set it up:
In Depth with .NET RegEx Balanced Grouping[^]

And then there is just the matter of going though all the hits to find the src bit.

Or you can use this tool and generate the expression yourself
Expresso - A Tool for Building and Testing Regular Expressions[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900