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.
Usually its NOT a good idea to unmask it by hand. There is a method in the Pattern class for this task:
As DOT( . ) is considered as a special character and split method of String expects a regular expression you need to do like this -
In java the special characters need to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another "\" !
split
takes a regex as argument. So you should pass"\."
instead of"."
because"."
is a metacharacter in regex.split()
accepts a regular expression, so you need to escape.
to not consider it as a regex meta character. Here's an exemple :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 "."
or telling the split method to split at at a character class:
Character classes are collections of characters. You could write
and filename would be split at every "-", ".", ";", "l", "d" or "7". Inside character classes, the "." is not a special character ("metacharacter").