LittleLawson的博客

不积跬步,无以至千里。

Java中的split()方法

Java中的split()方法

1.源码介绍:

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 

public String[] split(String regex) {
    return split(regex, 0);
}

2.中文翻译:
将这个字符串按照指定的正则表达式分割。
这个方法同两个参数的split(String,int)方法,其中的string是给定的字符串,与int参数相对应的就是0。拖尾部分的空字符不包含在返回的数组中。
例如:对于字符串boo:and:foo,如果使用如下的分隔符,将会产生如下的结果:

Regex Result 
: { "boo", "and", "foo" } 
o { "b", "", ":and:f" } 
  • 参数,regex:限定的正则表达式
  • 返回值:根据给定正则表达式计算出来的字符串数组
  • 异常:如果正则表达式语法错误

3.示例:

public void test2(){
    String str = "boo:and:foo";
    String[] result1 = str.split(":");
    for(String s: result1) {
        System.out.println(s);
    }
    /*result is:
    boo
    and
    foo
     */

    String [] result2 = str.split("o");
    for(String s: result2) {
        System.out.println(s);
    }
    /*result is:
    b

    :and:f
     */

}
public void test3(){
     String str = "boo.and.foo";
     /*
     1.because the symbol dot is a special symbol in regular expression,so you couldn't get any result
     2.symbol "." not be used as a common symbol but a regular expression?
      */
     String [] result = str.split(".");
     for(String s: result) {
         System.out.println(s);
     }

 }

注释:

阅读更多

扫码向博主提问

去开通我的Chat快问

LittleLawson

做一名真诚正直优秀的科技人员。
  • 擅长领域:
  • Kafka
  • Scala
  • Spark
  • Hadoop
  • Java
版权声明:注明原文链接,欢迎转载。 https://blog.csdn.net/liu16659/article/details/80342849
个人分类: Java
上一篇Java中valueOf()方法
下一篇《Scala cookBook》Chapter 9
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭