简体   繁体   中英

Strange String.split(“\n”) behavior

I tried to split name but none of the tries using split method worked

public void insertUpdate(DocumentEvent e) {
   String name="PU_Y"+
               "PU-x"+
               "Pu-z";

    split = name.split("\\r\\n");
    split = name.split("\r\n");
    split = name.split("[\r\n]+");
    split = name.split("[\\r\\n]+");
    split = name.split("\\r?\\n");
    // I tried using all the above to split above string but was not successful
}

Please help to split this string

Your string doesn't contain any line breaks at all. The fact that you've concatenated it on multiple lines doesn't do anything. Your statement is equivalent to:

String name = "PU_Y" + "PU-x" + "Pu-z";

or

String name = "PU_YPU-xPu-z";

You probably meant:

String name = "PU_Y\r\n" +
              "PU-x\r\n" +
              "Pu-z";

Retest your regular expressions with that change.

Your string has no linebreaks in it, every time you start a new line, you are concatenating strings as one statement.

Your string will be:

"PU_YPU-xPu-z"

If you want newlines, put a \\r\\n in the String before you terminate the string on each line:

String name="PU_Y\r\n"+
            "PU-x\r\n"+
            "Pu-z\r\n";

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