在 Java 中使用正则表达式划分数字列表



我有一个由数字列表组成的字符串,如下所示:

000000900100103010330200000005677890212126000020

使用单个正则表达式,我想获得许多结果,将原始字符串划分为不同长度的子字符串。我的意思是像

00000009 001 001 03 01 033 02 00000005677890212126 00002 0

所以我需要这些不同的"组"(我希望这是正确的词)

  • 00000009
  • 001
  • 001
  • 03
  • 01
  • 033
  • 02
  • 00000005677890212126
  • 00002
  • 0

每个元素的长度是固定的,永远不会改变。可能吗?

我试过:

[0-9]{8}[0-9]{3}[0-9]{3}[0-9]{2}...

但当然行不通

您需要

使用Pattern,如果找到,请使用Matcher.groupCountMatcher.group(int i)

static final Pattern p = Pattern.compile(
        "([0-9]{8})"
        +"([0-9]{3})"
        +"([0-9]{3})"
        +"([0-9]{2})"
        +"([0-9]{2})"
        +"([0-9]{3})"
        +"([0-9]{2})"
        +"([0-9]{20})"
        +"([0-9]{5})"
        +"([0-9]{1})");
private void test(String[] args) {
    // NB: I added one more 0 at the start.
    Matcher m = p.matcher("0000000900100103010330200000005677890212126000020");
    if ( m.find() ) {
        for ( int i = 1; i <= m.groupCount(); i++ ) {
            System.out.print(m.group(i)+" ");
        }
    }
}

指纹

00000009 001 001 03 01 033 02 00000005677890212126 00002 0

在Java 8中,您可以即时构建正则表达式。

static final List<Integer> fieldWidths = Arrays.asList(8,3,3,2,2,3,2,20,5,1);
static final Pattern p = Pattern.compile(
        fieldWidths.stream()
                .map(i -> "(\d{"+i+"})")
                .collect(Collectors.joining()));
我喜欢

上面的答案,这是一种没有正则表达式的替代方法,带有很好的旧 for 循环:

public static List<String> splitString(String inputString, int... lengths) {
    List<String> substrings = new ArrayList<String>();
    int start = 0;
    int end = 0;
    for(int length : lengths) {
        start = end;
        end = start + length;
        String substring  = inputString.substring(start, end);
        substrings.add(substring);
    }
    return substrings;
}
private void test(String[] args) {
    String s = "0000000900100103010330200000005677890212126000020";
    List<String> list = splitString(s,8,3,3,2,2,3,2,20,5,1);
}

最新更新