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];
I only need the first part of the string, that's why I return the first item. I ask because I noticed in the API that .
means any character, so now I'm stuck.
Wouldn't it be more efficient to use
if you only want what's up to the first dot?
Split uses regular expressions, where '.' is a special character meaning anything. You need to escape it if you actually want it to match the '.' character:
(one '\' to escape the '.' in the regular expression, and the other to escape the first one in the Java string)
Also I wouldn't suggest returning fn[0] since if you have a file named
something.blabla.txt
, which is a valid name you won't be returning the actual file name. Instead I think it's better if you use: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:delim
exists at end oftext
like ina,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 withPattern.DOTALL
flag).So for string like
"abc"
if we split on"."
split
method will["" "" "" ""]
,which means we will get as result empty array
[]
(with no elements, not even empty string), so we can't usefn[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
Bonus
You can also use other ways to escape that dot like
split("[.]")
split("\\Q.\\E")
Pattern.LITERAL
flagsplit(Pattern.quote("."))
and let regex do escaping for you.The split must be taking regex as a an argument... Simply change
"."
to"\\."
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.