Split string with dot as delimiter

后端 未结 13 2564
死守一世寂寞
死守一世寂寞 2020-11-22 11:14

I am wondering if I am going about splitting a string on a . the right way? My code is:

String[] fn = filename.split(\".\");
return fn[0];
         


        
13条回答
  •  星月不相逢
    2020-11-22 12:00

    the String#split(String) method uses regular expressions. In regular expressions, the "." character means "any character". You can avoid this behavior by either escaping the "."

    filename.split("\\.");
    

    or telling the split method to split at at a character class:

    filename.split("[.]");
    

    Character classes are collections of characters. You could write

    filename.split("[-.;ld7]");
    

    and filename would be split at every "-", ".", ";", "l", "d" or "7". Inside character classes, the "." is not a special character ("metacharacter").

提交回复
热议问题