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  
.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With