2017-08-24 79 views
-2

我需要將所有換行符替換爲\ n。 的問題是,如果字符串包含換行符的任何字符,我需要添加到行首4個空格和\ n用 n替換2個(以及更多)換行符與

例子:

The fat 
cat 



sat on the 
mat 

我需要什麼:

\n The fat\n cat\n\n\n\nsat on the\n mat 

當我使用的方法與string.replace,我得到這個

\n The fat\n cat\n \n \n sat on the\n mat 
+1

*「我需要添加到**第4行空格**開始**」但是您的示例顯示向行的**結尾**添加4個空格,而不是開頭。 – Andreas

+0

噢...對不起......我錯誤地附上錯誤的樣本。編輯問題 –

+0

'str = str.replaceAll(「[\ t] * \\ R [\ t] *」,「\ n」)'。演示請參見[regex101.com](https://regex101.com/r/L8cg3B/1)。 – Andreas

回答

1

使用str.replaceAll("(^|\n)(\\w)", "\n $2").replaceAll("\n", "\\\\n")