user1334130
user1334130

Reputation: 1191

Java Regex remove new lines, but keep spaces.

For the string " \n a b c \n 1 2 3 \n x y z " I need it to become "a b c 1 2 3 x y z".

Using this regex str.replaceAll("(\s|\n)", ""); I can get "abc123xyz", but how can I get spaces in between.

Upvotes: 8

Views: 38404

Answers (5)

Reimeus
Reimeus

Reputation: 159754

This will work:

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

Upvotes: 3

philip mudenyo
philip mudenyo

Reputation: 754

This will remove all spaces and newline characters

String oldName ="2547 789 453 ";
String newName = oldName.replaceAll("\\s", "");

Upvotes: 7

Joshua Michael Calafell
Joshua Michael Calafell

Reputation: 3107

Here is a pretty simple and straightforward example of how I would do it

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...

You could use this sample to verify that the last regex works:

class Foo {
    public static void main (String[] args) {
        String str = "FooBar";
        System.out.println(str.replaceAll(".(?=.)", "$0 "));
    }
}

Output: "F o o B a r"

More info on lookarounds in regex here: http://www.regular-expressions.info/lookaround.html

This approach makes it so that it would work on any string input and it is merely one more step added on to your original work, as to answer your question accurately. Happy Coding :)

Upvotes: 1

everag
everag

Reputation: 7662

If you really want to do this with Regex, this probably would do the trick for you

String str = " \n a b c \n 1 2 3 \n x y z ";

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

Upvotes: 1

Makoto
Makoto

Reputation: 106390

You don't have to use regex; you can use trim() and replaceAll() instead.

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

This will give you the string that you're looking for.

Upvotes: 12

Related Questions