使用正则表达式替换新行/返回空格 [英] Replace new line/return with space using regex
问题描述
对于知道某人的非常基本的问题。
Pretty basic question for someone who knows.
而不是从
"This is my text.
And here is a new line"
收件人:
"This is my text. And here is a new line"
我得到:
"This is my text.And here is a new line.
知道为什么吗?
L.replaceAll("[\\\t|\\\n|\\\r]","\\\s");
我想我找到了罪魁祸首。
I think I found the culprit.
On下一行我做了以下几行:
On the next line I do the following:
L.replaceAll( "[^a-zA-Z0-9|^!|^?|^.|^\\s]", "");
这似乎是导致我的问题。
And this seems to be causing my issue.
知道为什么吗?
我显然在尝试执行以下操作:删除所有非字符,并删除所有新行。
I am obviously trying to do the following: remove all non-chars, and remove all new lines.
推荐答案
\ s
是正则表达式中空格字符的快捷方式。它在字符串中没有意义。 ==>您不能在替换字符串中使用它。在那里你需要准确填写你想要插入的字符。如果这是一个空格,只需使用作为替换。
\s
is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " "
as replacement.
另一件事是:你为什么用3反斜杠作为转义序列? Java中有两个就足够了。并且您在字符类中不需要 |
(交替运算符)。
The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a |
(alternation operator) in a character class.
L.replaceAll("[\\t\\n\\r]+"," ");
备注
L
未更改。如果你想得到你需要做的结果
L
is not changed. If you want to have a result you need to do
String result = L.replaceAll("[\\t\\n\\r]+"," ");
测试代码:
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);
这篇关于使用正则表达式替换新行/返回空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!