-1

i'm creating a little programm atm and i need to replace every linebreak with a symbol, f.e. "#". So if i enter this text:

test1 
test2
test3

it should become

test1#test2#test3

i tried doing this:

String text2 = text.replaceAll("\n", "#"); //text is the inputed text

after some research i also tried

String text2 = text.replaceAll("\\\\n", "#");

because somebody says this has something to do with the compiler or idk. Any help is appreciated!

SyxDuLappen
  • 59
  • 2
  • 8
  • 1
    And how are you getting `text`? Does it, in fact, contain line-breaks? Also, `replace` is what you want; `replaceAll` takes a *regular expression*. – Elliott Frisch Apr 18 '16 at 18:32
  • text is a string variable and i get the text from a jTextPane like this: textPane.getText() @CubeJockey – SyxDuLappen Apr 18 '16 at 18:34

3 Answers3

3

Linebreaks are system dependent. On UNIX systems, it is "\n"; on Microsoft Windows systems it is "\r\n" . So it is better to make your code platform independent.

Use something like :

String text = rawText.replaceAll(System.lineSeparator(), "#");

Pleas note that System.lineSeparator() is available from Java 1.7.

Sumit Rathi
  • 693
  • 8
  • 15
  • 1
    Additionally if you are not going to use regex syntax then you can use `replace` instead of `replaceAll`. Both method will replace *all* occurrences of searched text (main difference between them is only regex syntax support). – Pshemo Apr 18 '16 at 20:04
0

Use an escaped backslash by typing \\. Also check for carriage returns \r\n.

String test = "test1\ntest2\r\ntest3";
System.out.println(test.replaceAll("(\\n|\\r\\n)", "#"));
flakes
  • 21,558
  • 8
  • 41
  • 88
0

replaceAll("\n", "#") should work fine if your lines ware separated only by \n. If it didn't work then it means your text is using other line separator like \r, \u0085 (next line - NEL) or most probably combination of \r\n.

Since replaceAll is using regex syntax, to match all line separators we can use \R (added to regex engine in Java 8). So you could try with.

String text2 = text.replaceAll("\\R", "#");

If you can't use Java 8 (like in case of Android applications) you could use regex which will represent \r\n or \n or \r:

String text2 = text.replaceAll("\r\n|\n|\r", "#");
//can be reduced to .replaceAll("\r?\n|\r", "#");
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269