使用正则表达式替换新行/返回空格

jas*_*n m 29 java regex

对于知道的人来说这是一个非常基本

而不是来自

"This is my text. 

And here is a new line"
Run Code Online (Sandbox Code Playgroud)

至:

"This is my text. And here is a new line"
Run Code Online (Sandbox Code Playgroud)

我明白了:

"This is my text.And here is a new line.
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?

L.replaceAll("[\\\t|\\\n|\\\r]","\\\s");
Run Code Online (Sandbox Code Playgroud)

我想我找到了罪魁祸首.

在下一行,我执行以下操作:

L.replaceAll( "[^a-zA-Z0-9|^!|^?|^.|^\\s]", "");
Run Code Online (Sandbox Code Playgroud)

这似乎是导致我的问题.

知道为什么吗?

我显然尝试执行以下操作:删除所有非字符,并删除所有新行.

ste*_*ema 52

\s是正则表达式中空格字符的快捷方式.它在字符串中没有意义.==>您不能在替换字符串中使用它.在那里你需要准确填写你想要插入的字符.如果这是一个空间,只需" "用作替代品.

另一件事是:为什么你使用3个反斜杠作为转义序列?Java中有两个就足够了.并且您不需要|在字符类中使用(交替运算符).

L.replaceAll("[\\t\\n\\r]+"," ");
Run Code Online (Sandbox Code Playgroud)

备注

L没有改变.如果你想得到一个结果,你需要做

String result =     L.replaceAll("[\\t\\n\\r]+"," ");
Run Code Online (Sandbox Code Playgroud)

测试代码:

String in = "This is my text.\n\nAnd here is a new line";
System.out.println(in);

String out = in.replaceAll("[\\t\\n\\r]+"," ");
System.out.println(out);
Run Code Online (Sandbox Code Playgroud)


Kep*_*pil 7

尝试

L.replaceAll("(\\t|\\r?\\n)+", " ");
Run Code Online (Sandbox Code Playgroud)

根据系统的不同,换行是\r\n或者只是\n.


Dim*_* II 7

不同操作系统的换行符不同 - '\r\n' 用于 Windows,'\n' 用于 Linux。

为安全起见,您可以使用正则表达式模式\R - Java 8 引入的换行符匹配器

String inlinedText = text.replaceAll("\\R", " ");
Run Code Online (Sandbox Code Playgroud)