Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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;.

like image 225
tolgap Avatar asked Jun 22 '13 16:06

tolgap


People also ask

How do I replace all line breaks in a string with br /> elements?

The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks. The pattern /g checks across all the string occurrences.

How do you add line break in Excel Find and Replace?

Steps to Find and Replace Line Break Select the cells that you want to search. On the keyboard, press Ctrl + F to open the Find and Replace dialog box, with the Find tab active. Click in the Find What box. On the keyboard, press Ctrl + J to enter the line break character.

How do you change a new line character in UNIX?

The `sed` command can easily split on \n and replace the newline with any character. Another delimiter can be used in place of \n, but only when GNU sed is used. When the \n is missing in the last line of the file, GNU sed can avoid printing \n.


1 Answers

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.

like image 148
anubhava Avatar answered Oct 13 '22 00:10

anubhava