Replace the new line with <br/"> and spaces with & emsp; inside the <code> tags
I would like to replace new lines and spaces with my analogs so that they fit correctly in my Android application.
I would like to know a better approach for this regex. I tried to do this in order to replace the newline lines with <br /> :
string.replaceAll("@<code>.*\\n*</code>@si", "<br />"); But that did not work. I could not think of anything to replace the double space.
So this is what I want to achieve:
From \n to <br /> and from "double unencrypted space" to   .
In Java, you can do this in 2 replacement calls:
string = string.replaceAll("\\r?\\n", "<br />"); string = string.replace(" ", "  "); 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(" ", "  "); m.appendReplacement(buf, grp); } m.appendTail(buf); // buf.toString() is your replaced string I deliberately used String#replace in the second call, because we are not actually using any regular expression.
Also, as @amn commented, you can wrap your string in <pre> and </pre> tags and avoid these replacements.