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?
Use below regex:
There's only really two newlines for UNIX and Windows OS.
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 you can use
for new line there is a property
Here as for your example,
Don't use regex!. You only need a plain-text match to replace
"\n"
.Use
replace()
to replace a literal string with another:Note that
replace()
still replaces all occurrences, as doesreplaceAll()
- the difference is thatreplaceAll()
uses regex to search.Looks good. You don't want 2 backslashes.
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum
No need for 2
backslashes
.Output =
hello --linebreak-- world