Java Regex removes newlines but retains spaces.

For the string " \nabc \n 1 2 3 \nxyz " I need it to become "abc 1 2 3 xyz" .

Using this regular expression str.replaceAll ("(\ s | \ n)", "); I can get" abc123xyz ", but how can I get the spaces between them.

+4
source share
5 answers

You do not need to use a regex; you can use trim() and replaceAll() .

  String str = " \nabc \n 1 2 3 \nxyz "; str = str.trim().replaceAll("\n ", ""); 

This will give you the string you are looking for.

+8
source

This will remove all spaces and newlines

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

This will work:

 str.replaceAll("^ | $|\\n ", "") 
+1
source

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

 String str = " \nabc \n 1 2 3 \nxyz "; str = str.replaceAll("^\\s|\n\\s|\\s$", ""); 
0
source

Here is a pretty simple and simple example of how I will do this

 String string = " \nabc \n 1 2 3 \nxyz "; //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 can use this example to check if the last regular expression works:

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

Exit: "F oo B ar"

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

This approach makes it work on any line input, and this is just one more step added to your original work to accurately answer your question. Happy coding :)

0
source

All Articles