有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法获取字符串拆分中的正则表达式示例

我无法从SUN tutorial of String split中获得这些示例:

例如"boo:and:foo"

Regex   Limit   Result  

o   5   { "b", "", ":and:f", "", "" }  
o   -2  { "b", "", ":and:f", "", "" }  
o   0   { "b", "", ":and:f" }  

我不明白结果
我了解到,对于负极限,模式应用的次数尽可能多,对于正极限,模式应用的次数为n-1次,等等

但我不明白在每种情况下,结果数组是如何形成的

例如,在第一种情况下,为什么我们在1位置有1“”,而在34位置有2“”
其余的也一样

有什么帮助吗


共 (2) 个答案

  1. # 1 楼答案

    案例1:

    非常直截了当

    第一步:处理boo:and:foo

    "b"  and  "o:and:foo"
    

    第2步:处理o:and:foo

    "" and ":and:foo"
    

    第3步:处理:和:foo

    ":and:f" and "o"
    

    第4步:处理o

    ""  and ""
    

    案例2:它是负极限,因此它会尽可能多次地应用“o”模式。因此同上。在那之后,我们剩下两个空字符串,没有更多的拆分应用

    案例3:0,与案例2相同,但它会丢弃尾随的空字符串。因此,它会丢弃最后两个字符串

  2. # 2 楼答案

    让我们从了解所有可能的拆分开始。我认为"b"":and:f"是清楚的

    空字符串来自ofo-""-obo-""-o)之间的拆分,以及在最后一个o之后的拆分,直到字符串的结尾,这也是一个空strng

    所以我们总共有5个匹配的字符串,拆分可以返回

    如果我们使用5-进行拆分,我们最多返回5个子字符串,whcih正好是我们拥有的5个子字符串,从而得到第一个输出:

    If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter

    如果我们使用-2进行拆分,我们将返回尽可能多的值(在本例中与5相同):

    If n is non-positive then the pattern will be applied as many times as possible and the array can have any length

    如果使用0进行拆分,我们将尽可能多地返回,但我们会丢弃所有尾随的空字符串:

    If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded

    注意:如果你想忽略o发生之间的空字符串,你应该使用regex "o+"进行分割,它尽可能多地占用o,因此o之间没有空字符串