Java字符串分割问题

3
我想知道为什么使用正则表达式将字符串

foo:and:boo

按照

o

进行分割后,结果中会出现空格? 因此输出看起来像这样 -

f "" and b

有人能解释一下为什么会出现 "" 吗?谢谢!


2
因为在 oo 之间没有字符。 - SubOptimal
3个回答

5
有人能解释一下为什么这里有个“”吗?
因为在“foo”中的oo之间没有任何东西。 正则表达式o会在字符串中的每个单独的o上拆分。
如果您使用了o+,那么您将不会有"",因为您正在说“在一个或多个o上拆分”: Live Example
class Example
{
    public static void main(String[] args)
    {
        String str = "foo:and:boo";
        test("Results from using just \"o\":", str, "o");
        test("Results from using \"o+\":",     str, "o+");
    }

    private static void test(String label, String str, String rex)
    {
        String[] results = str.split(rex);
        System.out.println(label);
        for (String result : results) {
            System.out.println("[" + result + "]");
        }
    }
}

输出:

仅使用“o”的结果:
[f]
[]
[:and:b]
使用“o+”后的结果:
[f]
[:and:b]

0

如果你了解正则表达式中索引的工作原理,我想你能很好地理解这个。

下图是从这里复制的。

enter image description here

正如您所看到的,尽管 "foo" 的长度仅为 3 个字符,但起始索引为 0,结束索引为 3。

现在,如果您说要在 "o" 上分割(仅出现一次 o),您会发现 cell1(o) 和 cell2(o) 之间没有任何内容,因此它会返回空字符串。正如其他人提到的,如果您使用 "o+"(字母 o 的一个或多个出现)进行分割,您将不会得到空字符串。希望我表述清楚了。


0

按照 "o" 进行分割将会在每个找到的 "o" 处进行分割:

"ok".split("o");

给出结果:

  1. "" ->索引0(包括)到索引1(不包括)
  2. k ->索引1(包括)到索引2(不包括)

因为索引0匹配了你的正则表达式“o”。但是为什么foo也没有返回“”呢?

split的文档说明如下:

尾随的空字符串因此不包含在结果数组中。

尾随指的是正则表达式的末尾。如果在“boo”后面添加一些内容:

String source = "foo:and:boot"; String[] os = source.split("o");

System.out.println(String.format("Size of result is [%s]", os.length));
for (int i = 0; i < os.length; i++) {
    System.out.println(i + " " + os[i]);
}

输出结果为:

Size of result is [5]
0 f
1 
2 :and:b
3 
4 t

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接