Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex remove new lines, but keep spaces.

Tags:

java

regex

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.

like image 990
user1334130 Avatar asked Aug 18 '12 01:08

user1334130


1 Answers

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.

like image 169
Makoto Avatar answered Oct 20 '22 17:10

Makoto