「$$ $$」または「$ $」または「\[ \] 内の「\r\n」を除いて、すべての「\r\n」を 2 つのバックスラッシュ + 改行「\\ \r\n」に置き換えたい"。(これはラテックス構文です)
次のテキスト
1.$$ Test
2.
3.$$ $
4. $
5. Test $
6.
7. $
8.
9. Test
する必要があります
1.$$ Test
2.
3.$$ $
4. $ \\
5. Test $
6.
7. $ \\
8. \\
9. Test
私の試行の 1 つ: 最初に $$ $$ または $ $ または \[ \] の間の改行を --newline- に置き換えました。次に、すべての改行を二重の改行に置き換えました (ラテックスでは \ は二重の改行に等しい) . 次に、 --newline-- を新しい行に置き換えました。
private static String replaceNewLines(String original) {
String text = original;
text = replaceBetween(text, "\\[", "\\]");
text = replaceBetween(text, "$$", "$$");
text = replaceBetween(text, "$", "$");
text = text.replace("\r\n", "\r\n\r\n").replace("--newline--", "\r\n");
return text;
}
private static String replaceBetween(String text, String start, String end) {
int i = text.indexOf(start);
while (i >= 0) {
int j = text.indexOf(end, i + 1);
String before = text.substring(0, i);
String after = text.substring(j);
text = before + text.substring(i, j).replace("\r\n", "--newline--")
+ after;
i = text.indexOf(start, j + 1);
}
return text;
}