Ced
Ced

Reputation: 17367

replacing <img> by <img></img> in a string

I want to replace every <img> tag with closing <img></img> tags in a string. The string is actually an html document where the img tag are generated by me and always look like this :

<img src="some_source.jpg" style="some style attributes and values">

Src is user input so it can be anything. I made a regex expression, not sure if correct because it's my first time using it but upon testing it was working. The problem is that I don't know how to keep the content of the src.

/<img\ssrc=".+?"\sstyle=".+?">/g

But I have difficulties replacing the tags in the string.

and all I got is this:

    Pattern p = Pattern.compile("/<img\\ssrc=\".+?\"\\sstyle=\".+?\">/g");
    Matcher m = p.matcher(str);
    List<String> imgStrArr = new ArrayList<String>();
    while (m.find()) {
        imgStrArr.add(m.group(0));
    }
    Matcher m2 = p.matcher(str);

Upvotes: 2

Views: 1295

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

You can use the following regex to match:

(<img[^>]+>)

And replace with $1</img>

Code:

str = str.replaceAll("(<img[^>]+>)", "$1</img>");

Edit: Considering @MarcusMüller's advice you can do the following:

Regex: (<img[^>]+)>

Replace with $1/>

Code:

str = str.replaceAll("(<img[^>]+)>", "$1/>");

Upvotes: 4

Federico Piazza
Federico Piazza

Reputation: 31035

You don't have to use Pattern and Matcher classes, you can use the regular replace method like this:

str = str.replaceAll("(<img.*?>)", "$1</img>");

IdeOne working demo

Upvotes: 1

Related Questions