Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace new line/return with space using regex

Tags:

java

regex

Pretty basic question for someone who knows.

Instead of getting from

"This is my text.   And here is a new line" 

To:

"This is my text. And here is a new line" 

I get:

"This is my text.And here is a new line. 

Any idea why?

L.replaceAll("[\\\t|\\\n|\\\r]","\\\s"); 

I think I found the culprit.

On the next line I do the following:

L.replaceAll( "[^a-zA-Z0-9|^!|^?|^.|^\\s]", ""); 

And this seems to be causing my issue.

Any idea why?

I am obviously trying to do the following: remove all non-chars, and remove all new lines.

like image 347
jason m Avatar asked Jun 15 '12 10:06

jason m


2 Answers

\s is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " " as replacement.

The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a | (alternation operator) in a character class.

L.replaceAll("[\\t\\n\\r]+"," "); 

Remark

L is not changed. If you want to have a result you need to do

String result =     L.replaceAll("[\\t\\n\\r]+"," "); 

Test code:

String in = "This is my text.\n\nAnd here is a new line"; System.out.println(in);  String out = in.replaceAll("[\\t\\n\\r]+"," "); System.out.println(out); 
like image 96
stema Avatar answered Sep 20 '22 02:09

stema


Try

L.replaceAll("(\\t|\\r?\\n)+", " "); 

Depending on the system a linefeed is either \r\n or just \n.

like image 38
Keppil Avatar answered Sep 20 '22 02:09

Keppil