java中split的用法及注意
(2011-12-30 11:26:50)
标签:
杂谈 |
分类: JAVA |
java中的String字符串属于常量类,使用的场合比较多。其中字符串的剪切使用更是频繁,split是一种很好,也是使用很频繁的字符串剪切方式,对于以"."和"|"为分隔符的字符串,用split剪切时需要转义一下,否则无效。注意代码中的"\\."和"\\|"
java.lang.String
split方法:将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
stringObj.split(regex,[limit])
stringObj:必选项。要被分解的
regex:必选项。定界正则表达式。
limit:可选项。该值用来限制返回数组中的元素个数。如果不选择默认为0,此时结果数组返回全部分割子串,其中不包括结尾空字符串。
返回:字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组。
抛出PatternSyntaxException:如果正则表达式的语法无效
从以下版本开始:1.4
说明:split
示例1:
输出:
This
is
a
simple
example!
示例2:
输出:
This
is
a
simple
example!
示例3:
输出:
This
is
a simple example!
示例4:
输出:
This
is
a
simple
example!
再看示例5:
输出:
T
h
i
s
|
i
s
|
a
|
s
i
m
p
l
e
|
e
x
a
m
p
l
e!
示例5改正:
输出:
This
is
a
simple
example!
示例6:
输出:
You
and
me
from
oneworld!
另外像matches(String regex),replaceAll(String regex,String replacement)这类函数的处理都要用到正则表达。