Split string with dot as delimiter

2018-12-31 22:33发布

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.

11条回答
冷夜・残月
2楼-- · 2018-12-31 23:01

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) 
查看更多
情到深处是孤独
3楼-- · 2018-12-31 23:02

As DOT( . ) is considered as a special character and split method of String expects a regular expression you need to do like this -

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

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 "\" !

查看更多
笑指拈花
4楼-- · 2018-12-31 23:07

split takes a regex as argument. So you should pass "\." instead of "." because "." is a metacharacter in regex.

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 23:08

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

String[] fn = filename.split("\\."); 
return fn[0];
查看更多
若你有天会懂
6楼-- · 2018-12-31 23:08
String str="1.2.3";
String[] cats = str.split(Pattern.quote("."));
查看更多
何处买醉
7楼-- · 2018-12-31 23:12

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").

查看更多
登录 后发表回答