Java Regex remove new lines, but keep spaces.

后端 未结 5 1299
名媛妹妹
名媛妹妹 2021-01-18 10:21

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|

5条回答
  •  野的像风
    2021-01-18 10:57

    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 :)

提交回复
热议问题