Tuesday, October 16, 2012

Extract img using regex

Hi All

If you want to extract image from HTML code and want to separate text with html ,
I am sure below code help you a lot :

 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ImgTest {

    public static void main(String[] args) {

            String s = "This is a jignesh<img src=\"test.html\" /> text";

            Pattern p = Pattern.compile("[<](/)?img[^>]*[>]");

            Matcher m = p.matcher(s);

            if (m.find()) {

              String src = m.group();

              System.out.println(src);

            }

            s = s.replaceAll("[<](/)?img[^>]*[>]", "");

            System.out.println(s);

    }

} 
OUTPUT :

<img src="test.html" />

This is a jignesh text  



Cheers !!!!