Reputation: 9778
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  
.
Upvotes: 7
Views: 9839
Reputation: 785068
In Java you can do that in 2 replace calls:
string = string.replaceAll("\\r?\\n", "<br />");
string = string.replace(" ", "  ");
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 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