Tim
Tim

Reputation: 4365

Java Regex - Using String's replaceAll method to replace newlines

I have a string and would like to simply replace all of the newlines in it with the string " --linebreak-- ".

Would it be enough to just write:

string = string.replaceAll("\n", " --linebreak-- ");

I'm confused with the regex part of it. Do I need two slashes for the newline? Is this good enough?

Upvotes: 48

Views: 91800

Answers (8)

Pshemo
Pshemo

Reputation: 124215

Since Java 8 regex engine supports \R which represents any line separator (little more info: https://stackoverflow.com/a/31060125/1393766).

So if you have access to Java 8 or above you can use

string = string.replaceAll("\\R", " --linebreak-- ");

Upvotes: 38

Anand Rockzz
Anand Rockzz

Reputation: 6658

In my case I wanted to replace with literal '\n' so I escaped the \ with another \ like so

String input = "a\nb\nc\nd";
/*
a
b
c
d 
*/
input = input.replace("\n", "\\n");
System.out.println(input); // a\nb\nc\nd

Upvotes: 0

Matt
Matt

Reputation: 3760

Just adding this for completeness, because the 2 backslash thing is real.

Refer to @dasblinkenlight answer in the following SO question (talking about \t but it applies for \n as well):

java, regular expression, need to escape backslash in regex

"There are two interpretations of escape sequences going on: first by the Java compiler, and then by the regexp engine. When Java compiler sees two slashes, it replaces them with a single slash. When there is t following a slash, Java replaces it with a tab; when there is a t following a double-slash, Java leaves it alone. However, because two slashes have been replaced by a single slash, regexp engine sees \t, and interprets it as a tab."

Upvotes: 2

Bohemian
Bohemian

Reputation: 424973

Don't use regex!. You only need a plain-text match to replace "\n".

Use replace() to replace a literal string with another:

string = string.replace("\n", " --linebreak-- ");

Note that replace() still replaces all occurrences, as does replaceAll() - the difference is that replaceAll() uses regex to search.

Upvotes: 79

JavaLearner
JavaLearner

Reputation: 322

for new line there is a property

System.getProperty("line.separator")

Here as for your example,

string.replaceAll("\n", System.getProperty("line.separator"));

Upvotes: 1

kandarp
kandarp

Reputation: 5047

Use below regex:

 s.replaceAll("\\r?\\n", " --linebreak-- ")

There's only really two newlines for UNIX and Windows OS.

Upvotes: 47

RanRag
RanRag

Reputation: 49537

No need for 2 backslashes.

 String string = "hello \n world" ;
 String str = string.replaceAll("\n", " --linebreak-- ");
 System.out.println(str);

Output = hello --linebreak-- world

Upvotes: 4

mikey
mikey

Reputation: 5160

Looks good. You don't want 2 backslashes.

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum

Upvotes: 1

Related Questions