关于JAVA中split()函数遇到的一点问题

 
古城
@ 2009.03.26
分类:技术笔记
点击:6833  评论:0
 
 
 

    很简单的,就是想分割一个文件路径字符串,取它的扩展名。

    String file=new String("c:\\test\\file.exe");
    String[] temp = file.split(".");

    程序运行到这里,就异常终止了。想想以前用split分割很多种符号,都没问题。随手试了试split("\\"),依然失败。又换了其他的各种符号":"、"##"等等却又没问题。难道"."和"\\"有什么不对么?

    在仔细看看JDK的文档:

String[] java.lang.String.split(String regex)

split
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }


Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
Throws:
PatternSyntaxException - if the regular expression's syntax is invalid
Since:
1.4
See Also:
Pattern

    清清楚楚的写着参数是String regex,一个regular expression,正则表达式。哎,以前没认真看过,一直当成普通的字符串在用了,只是运气好,恰好没出错。知错就改:

    改成String[] temp = file.split("\\.");或者String[] temp = file.split("[.]");就可以了。至于那个"\\"分割的话,用String[] temp = file.split("\\\\");就可以了。

 
 
 
 
 

本文评论

 
 

发表评论

你的评论
← 填你的昵称
以下内容非必填,可根据需要填写
← 可以展示在你的评论上方
← 不会在页面展示
← 不会在页面展示
← 只给我看?勾选上
这是一个别人称之为角落的世界
幸而,它的确是我的世界