Java正则表达式删除换行符,但保留空格。

8
对于字符串" \n a b c \n 1 2 3 \n x y z ",我需要它变成"a b c 1 2 3 x y z"。您可以使用以下正则表达式str.replaceAll("(\s|\n)", "")得到"abc123xyz",但是如何在它们之间获得空格呢?
5个回答

12

你不一定需要使用正则表达式;你可以改用 trim()replaceAll()

 String str = " \n a b c \n 1 2 3 \n x y z ";
 str = str.trim().replaceAll("\n ", "");

这将为您提供您要查找的字符串。


@pmartin8 你想告诉那个满意于此的OP吗? - Makoto

7
这将删除所有空格和换行符。
String oldName ="2547 789 453 ";
String newName = oldName.replaceAll("\\s", "");

3
这将起作用:
str = str.replaceAll("^ | $|\\n ", "")

1
这是一个相当简单和直接的例子,展示了我如何实现它。
String string = " \n a   b c \n 1  2   3 \n x y  z "; //Input
string = string                     // You can mutate this string
    .replaceAll("(\s|\n)", "")      // This is from your code
    .replaceAll(".(?=.)", "$0 ");   // This last step will add a space
                                    // between all letters in the 
                                    // string...

你可以使用这个示例来验证最后一个正则表达式是否有效:
class Foo {
    public static void main (String[] args) {
        String str = "FooBar";
        System.out.println(str.replaceAll(".(?=.)", "$0 "));
    }
}

输出:"F o o B a r"
更多关于正则表达式lookaround的信息在这里:http://www.regular-expressions.info/lookaround.html 这种方法可以使它适用于任何字符串输入,并且只是在您的原始工作中添加了一个步骤,以准确回答您的问题。快乐编程 :)

1
如果你真的想用正则表达式来做这件事,这个方法可能适合你。
String str = " \n a b c \n 1 2 3 \n x y z ";

str = str.replaceAll("^\\s|\n\\s|\\s$", "");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接