Why does .split(“\\”) generate an exception?

前端 未结 5 1456
死守一世寂寞
死守一世寂寞 2021-01-25 03:35

I have a String representing a directory, where \\ is used to separate folders. I want to split based on \"\\\\\":

String address = \"C         


        
5条回答
  •  广开言路
    2021-01-25 04:15

    As others have suggested, you could use:

    String[] separated = address.split("\\\\");
    

    or you could use:

    String[] separated = address.split(Pattern.quote("\\")); 
    

    Also, for reference:

    String address = "C:\saeed\test";
    

    will not compile, since \s is not a valid escape sequence. Here \t is interpreted as the tab character, what you actually want is:

    String address = "C:\\saeed\\test";
    

    So, now we see that in order to get a \ in a String, we need "\\".

    The regular expression \\ matches a single backslash since \ is a special character in regex, and hence must be escaped. Once we put this in quotes, aka turn it into a String, we need to escape each of the backslashes, yielding "\\\\".

提交回复
热议问题