在每个第n个位置拆分一个字符串

时间:2012-09-06 08:12:53

标签: java regex string split

我使用这个正则表达式在每个第三个位置分割一个字符串:

String []thisCombo2 = thisCombo.split("(?<=\\G...)");

其中G之后的3个点表示要分割的每个第n个位置。在这种情况下,3个点表示每3个位置。一个例子:

Input: String st = "123124125134135145234235245"
Output: 123 124 125 134 135 145 234 235 245.

我的问题是,如何让用户控制必须拆分字符串的位置数?换句话说,如何制作用户控制的3个点,n个点?

5 个答案:

答案 0 :(得分:44)

为了大幅提升性能,另一种方法是在循环中使用substring()

public String[] splitStringEvery(String s, int interval) {
    int arrayLength = (int) Math.ceil(((s.length() / (double)interval)));
    String[] result = new String[arrayLength];

    int j = 0;
    int lastIndex = result.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        result[i] = s.substring(j, j + interval);
        j += interval;
    } //Add the last bit
    result[lastIndex] = s.substring(j);

    return result;
}

示例:

Input:  String st = "1231241251341351452342352456"
Output: 123 124 125 134 135 145 234 235 245 6.

它不像stevevls' solution那么短,但它的方式更有效(见下文),我认为将来调整会更容易,当然这取决于你的情况。


性能测试(Java 7u45)

2,000 个字符长字符串 - 间隔 3

split("(?<=\\G.{" + count + "})")性能(以毫秒为单位):

7, 7, 5, 5, 4, 3, 3, 2, 2, 2

splitStringEvery()substring())表现(以毫秒为单位):

2, 0, 0, 0, 0, 1, 0, 1, 0, 0

2,000,000 个字符长字符串 - 间隔 3

split()性能(以毫秒为单位):

207, 95, 376, 87, 97, 83, 83, 82, 81, 83

splitStringEvery()性能(以毫秒为单位):

44, 20, 13, 24, 13, 26, 12, 38, 12, 13

2,000,000 个字符长字符串 - 间隔 30

split()性能(以毫秒为单位):

103, 61, 41, 55, 43, 44, 49, 47, 47, 45

splitStringEvery()性能(以毫秒为单位):

7, 7, 2, 5, 1, 3, 4, 4, 2, 1

<强>结论:

splitStringEvery()方法快得多(即使在the changes in Java 7u6之后),并且当间隔变得更高时会升级

即用型测试代码:

pastebin.com/QMPgLbG9

答案 1 :(得分:29)

您可以使用大括号运算符指定角色必须出现的次数:

String []thisCombo2 = thisCombo.split("(?<=\\G.{" + count + "})");

大括号是一个方便的工具,因为您可以使用它来指定精确的计数或范围。

答案 2 :(得分:18)

使用Google Guava,您可以使用Splitter.fixedLength()

  

返回一个拆分器,它将字符串分成给定长度的片段

Splitter.fixedLength(2).split("abcde");
// returns an iterable containing ["ab", "cd", "e"].

答案 3 :(得分:0)

如果要构建该正则表达式字符串,可以将分割长度设置为参数。

public String getRegex(int splitLength)
{
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < splitLength; i++)
        builder.append(".");

    return "(?<=\\G" + builder.toString() +")";
}

答案 4 :(得分:0)

private String[] StringSpliter(String OriginalString) {
    String newString = "";
    for (String s: OriginalString.split("(?<=\\G.{"nth position"})")) { 
        if(s.length()<3)
            newString += s +"/";
        else
            newString += StringSpliter(s) ;
    }
    return newString.split("/");
}