代码之家  ›  专栏  ›  技术社区  ›  Iain Sproat

Java等价于python的字符串分区

  •  4
  • Iain Sproat  · 技术社区  · 16 年前

    Java的string split(regex)函数在regex的所有实例上进行拆分。Python的分区函数只在给定分隔符的第一个实例上进行拆分,并返回一个元组{left,separator,right}。

    如何实现Java中分区的功能?

    例如

    "foo bar hello world".partition(" ")
    

    应该变成

    "foo", " ", "bar hello world"
    
    • 没有你我怎么能做到 外部图书馆?

    • 它能在没有外部库和Regex的情况下实现吗?

    注意。我没有寻找split(“,2),因为它不返回分隔符。

    5 回复  |  直到 16 年前
        1
  •  5
  •   Community Mohan Dere    6 年前

    这个 String.split(String regex, int limit) 很接近你想要的。根据文件:

    这个 limit 参数控制应用阵列的次数,从而影响结果阵列的长度。

    • n 大于零,则最多应用该模式 n - 1 n ,数组的最后一个条目将包含最后一个匹配分隔符之外的所有输入。
    • 如果 n 如果为非正,则将尽可能多次应用阵列,并且阵列可以具有任何长度。
      • 如果 n 如果为零,则将尽可能多次应用阵列,阵列可以具有任何长度,并且 尾随的空字符串将被丢弃。

    下面是一个例子来说明这些差异( as seen on ideone.com

    static void dump(String[] ss) {
        for (String s: ss) {
            System.out.print("[" + s + "]");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        String text = "a-b-c-d---";
    
        dump(text.split("-"));
        // prints "[a][b][c][d]"
    
        dump(text.split("-", 2));
        // prints "[a][b-c-d---]"
    
        dump(text.split("-", -1));
        // [a][b][c][d][][][]
        
    }
    

    保留分隔符的分区

    如果您需要与分区类似的功能,并且还希望获得由任意模式匹配的分隔符字符串,则可以使用 Matcher substring 在适当的指数。

    下面是一个例子( as seen on ideone.com ):

    static String[] partition(String s, String regex) {
        Matcher m = Pattern.compile(regex).matcher(s);
        if (m.find()) {
            return new String[] {
                s.substring(0, m.start()),
                m.group(),
                s.substring(m.end()),
            };
        } else {
            throw new NoSuchElementException("Can't partition!");
        }
    }
    public static void main(String[] args) {
        dump(partition("james007bond111", "\\d+"));
        // prints "[james][007][bond111]"
    }
    

    正则表达式 \d+ \d + ).

        2
  •  5
  •   Andrzej Doyle    16 年前

    确切地 你想要什么,有一个 second version of split

    所以如果你打电话(用Java):

    "foo bar hello world".split(" ", 2);
    

    你会得到阵列:

    ["foo", "bar hello world"]
    

    需要这最后一点,你需要自己去做,但希望你特别想要的是能够限制分裂的数量。

        3
  •  2
  •   Igor Artamonov    16 年前

    这个怎么样:

    String partition(String string, String separator) {
        String[] parts = string.split(separator, 2);
        return new String[] {parts[0], separator, parts[1]};
    }
    

    顺便说一句,您必须在以下位置添加一些输入/结果检查:)

        4
  •  0
  •   Favonius    16 年前

    用途:

    "foo bar hello world".split(" ",2)
    

    默认情况下,分隔符是空白

        5
  •  0
  •   Michael Borgwardt    16 年前

    是否已有提供此实用程序的外部库?

    据我所知没有。

    如果没有外部库,我将如何实现它? 它能在没有外部库和Regex的情况下实现吗?

    当然,这一点问题都没有;只是使用 String.indexOf() 和 String.substring()