Split string with dot as delimiter

后端 未结 13 2205
死守一世寂寞
死守一世寂寞 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:09

    Note: Further care should be taken with this snippet, even after the dot is escaped!

    If filename is just the string ".", then fn will still end up to be of 0 length and fn[0] will still throw an exception!

    This is, because if the pattern matches at least once, then split will discard all trailing empty strings (thus also the one before the dot!) from the array, leaving an empty array to be returned.

    0 讨论(0)
  • 2020-11-22 12:10

    Wouldn't it be more efficient to use

     filename.substring(0, filename.indexOf("."))
    

    if you only want what's up to the first dot?

    0 讨论(0)
  • 2020-11-22 12:13

    Usually its NOT a good idea to unmask it by hand. There is a method in the Pattern class for this task:

    java.util.regex
    static String quote(String s) 
    
    0 讨论(0)
  • 2020-11-22 12:13

    The solution that worked for me is the following

    filename.split("[.]");

    0 讨论(0)
  • 2020-11-22 12:14

    split() accepts a regular expression, so you need to escape . to not consider it as a regex meta character. Here's an example :

    String[] fn = filename.split("\\."); 
    return fn[0];
    
    0 讨论(0)
  • 2020-11-22 12:18

    The split must be taking regex as a an argument... Simply change "." to "\\."

    0 讨论(0)
提交回复
热议问题