7
4

1 回答 1

13

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.

于 2013-06-22T17:22:21.117 回答