java中split分割"."的问题

今天使用split分割"."的时候居然失败了,经过百度发现原来要加转义字符才行。

正确的写法:

String test="1.2.3";
String[] s1=test.split("\\.");

结果:

如果不加转义就会分割失败,返回一个空的字符串数组。

API中是这样写的:

public String[] split(String regex)

 Splits this string around matches of the given regular expression. 

它的参数并不是要分割的字符串,而是一个表达式,因此像*、+等都要加转义

但是使用substring函数就没有这个问题

例如取文件名的后缀可以这样写:

String fileSuffix=fileName.substring(fileName.lastIndexOf(".")+1);

 

posted @ 2017-04-27 10:15  MasterGuo  阅读(602)  评论(0编辑  收藏  举报
我的个人博客\ (•◡•) /