Split string with dot as delimiter

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

    I see only solutions here but no full explanation of the problem so I decided to post this answer

    Problem

    You need to know few things about text.split(delim). split method:

    1. accepts as argument regular expression (regex) which describes delimiter on which we want to split,
    2. if delim exists at end of text like in a,b,c,, (where delimiter is ,) split at first will create array like ["a" "b" "c" "" ""] but since in most cases we don't really need these trailing empty strings it also removes them automatically for us. So it creates another array without these trailing empty strings and returns it.

    You also need to know that dot . is special character in regex. It represents any character (except line separators but this can be changed with Pattern.DOTALL flag).

    So for string like "abc" if we split on "." split method will

    1. create array like ["" "" "" ""],
    2. but since this array contains only empty strings and they all are trailing they will be removed (like shown in previous second point)

    which means we will get as result empty array [] (with no elements, not even empty string), so we can't use fn[0] because there is no index 0.

    Solution

    To solve this problem you simply need to create regex which will represents dot. To do so we need to escape that .. There are few ways to do it, but simplest is probably by using \ (which in String needs to be written as "\\" because \ is also special there and requires another \ to be escaped).

    So solution to your problem may look like

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

    Bonus

    You can also use other ways to escape that dot like

    • using character class split("[.]")
    • wrapping it in quote split("\\Q.\\E")
    • using proper Pattern instance with Pattern.LITERAL flag
    • or simply use split(Pattern.quote(".")) and let regex do escaping for you.

提交回复
热议问题