Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
Tim Avatar asked Mar 24 '12 03:03

Tim


People also ask

Does replaceAll replace original string?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

How do you replace a space in a new line in a string in Java?

L. replaceAll( "[^a-zA-Z0-9|^!|

What is the difference between Replace () and replaceAll ()?

The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.


2 Answers

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.

like image 60
Bohemian Avatar answered Sep 28 '22 05:09

Bohemian


Use below regex:

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

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

like image 33
kandarp Avatar answered Sep 28 '22 03:09

kandarp