Replace '\ n' with ',' in java

I want to take data from the user like Stringand replace the newline character \nwith,

I tried:

String test ="s1\ns2\ns3\ns4"; System.out.println(test.replaceAll("\n",","));

The output was s1, s2, s3, s4

But when I try to use the same code, getting input from the user interface, it does not work.

When I debug it, the string test (which I am hard-coded) is processed as

s1

s2

s3

s4

but the string from the UI is " s1\ns2\ns3\ns4".

Please suggest what is wrong.

+4
source share
4 answers

\n - . , n, :

String test ="s1\ns2\ns3\ns4";
System.out.println(test.replaceAll("\\n",","));

Update:

System.lineSeparator(); \n.

System.out.println(test.replaceAll(System.lineSeparator(),","));
+6

java.util.regex.Pattern :

- , . :

( ) ('\n'), ( "\ r\n" ), ('\ r'), ('\ u0085'), ('\ u2028') ('\ u2029).

, textarea, \r\n (CR/LF).

regex [\r\n]+

+2

anacron, "\n" "\n", "\\n".

Java

String test ="s1\\ns2\\ns3\\ns4";

String test ="s1\ns2\ns3\ns4";

charachter, '\' Java charachter '\\'.

+1

Regex:

public class Program
{
    public static void main(String[] args) {
        String str = "s1\ns2\ns3\ns4";
        str = str.replaceAll("(\r\n|\n)", ",");
        System.out.println(str);
    }
}

outout: s1, s2, s3, s4

+1

Source: https://habr.com/ru/post/1671333/


All Articles