tolgap
tolgap

Reputation: 9778

Replace newline with <br/> and spaces with   inside <code> tags

I would like to replace newlines and spaces with their counterparts so they get styled correctly in my android app.

I would like to know the best approach for this regex. I've tried to do this to replace newlines with <br />:

string.replaceAll("@<code>.*\\n*</code>@si", "<br />");

But it didn't work. For the double space replacing, I haven't been able to come up with anything.

So This is what I want to achieve:

From \n to <br />, and from "double unencoded space" to &emsp;.

Upvotes: 7

Views: 9839

Answers (1)

anubhava
anubhava

Reputation: 785068

In Java you can do that in 2 replace calls:

string = string.replaceAll("\\r?\\n", "<br />");
string = string.replace("  ", " &emsp;");

EDIT:

Matcher m = Pattern.compile("(?s)(?i)(?<=<code>)(.+?)(?=</code>)").matcher(string);
StringBuffer buf = new StringBuffer();
while (m.find()) {
    String grp = m.group(1).replaceAll("\\r?\\n", "<br />");
    grp = grp.replace("  ", " &emsp;");
    m.appendReplacement(buf, grp);
}
m.appendTail(buf);
// buf.toString() is your replaced string

I purposefully used String#replace in 2nd call because we're not really using any regex there.

Also as @amn commented you can wrap your string in <pre> and </pre> tags and avoid these replacements.

Upvotes: 13

Related Questions