Java Regex - Using String's replaceAll method

2019-01-14 06:08发布

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?

7条回答
放荡不羁爱自由
2楼-- · 2019-01-14 06:12

Use below regex:

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

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

查看更多
走好不送
3楼-- · 2019-01-14 06:14

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

string = string.replaceAll("\\R", " --linebreak-- ");
查看更多
再贱就再见
4楼-- · 2019-01-14 06:22

for new line there is a property

System.getProperty("line.separator")

Here as for your example,

string.replaceAll("\n", System.getProperty("line.separator"));
查看更多
叼着烟拽天下
5楼-- · 2019-01-14 06:25

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.

查看更多
▲ chillily
6楼-- · 2019-01-14 06:27
再贱就再见
7楼-- · 2019-01-14 06:32

No need for 2 backslashes.

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

Output = hello --linebreak-- world

查看更多
登录 后发表回答