简体   繁体   中英

Replace '\n' by ',' in java

I want to take input from user as String and replace the newline character \n with ,

I tried:

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

Output was s1,s2,s3,s4

But when I try the same code by getting input from UI it's not working.

When I debug it the string test(which I hardcoded) is treated as,

s1

s2

s3

s4

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

Please suggest what is wrong.

\\n is the new line character. If you need to replace that actual backslash character followed by n , Then you need to use this:

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

Update:

You can use the System.lineSeparator(); instead of the \\n character.

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

As anacron already pointed out '\\n' is a special charachter and different to the user input "\\n", because the user input is transformed to "\\\\n".

The Java String after user input will look like

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

and not like your test string

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

The user will input single charachter and the keyboard '\\' is transformed to Java charachter '\\\\'.

java.util.regex.Pattern documentation specifies Line terminators as :

A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:

A newline (line feed) character ('\\n'), A carriage-return character followed immediately by a newline character ("\\r\\n"), A standalone carriage-return character ('\\r'), A next-line character ('\…'), A line-separator character ('\
'), or A paragraph-separator character ('\
).

Your line terminator, from textarea, are \\r\\n (CR/LF).

regex for that is [\\r\\n]+

Using 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

If someone will get from UI \\n in text and want remove one \ to get next line sign \n then can use this:

        String text = "text\\ntext\\ntext\\ntext";
    System.out.println(text.replaceAll("\\\\n", "\n"));

https://i.stack.imgur.com/nAv8d.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM