Dennis Hepworth
Dennis Hepworth

Reputation: 11

Java - regular expression fixed length split into array

I've seen an example once before, but cannot find it again on how to split a fixed length data stream into an array using Regular expressions. Is this actually possible, is so, does anyone have a basic example?

  08/14       1351 XMGYV4      AOUSC             LTC                        .000          .000 VDPJU01PMP 11AUG14:15:17:05.99     

I want to store each value into a separated value in an array without using substring.

Upvotes: 1

Views: 695

Answers (3)

user1043279
user1043279

Reputation:

Perhaps consider Krayo's solution String[] array = s.split( "\\s+" );?

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109557

The problem in this case is, that there is no fixed field size for every column. Hence one needs to match on individual widths, enumerated.

    String s = "  08/14       1351 XMGYV4      "
        + "AOUSC             LTC                        .000          .000 "
        + "VDPJU01PMP 11AUG14:15:17:05.99     ";
    Pattern pattern = Pattern.compile("(.{7,7})(.{11,11})(.)(.{12,12})(.{18,18})(.*)");
    Matcher m = pattern.matcher(s);
    if (m.matches()) {
        for (int i = 1; i <= m.groupCount(); ++i) {
            String g = m.group(i);
            System.out.printf("[%d] %s%n", i, g);
        }
    }

This is a listing of groups like (.{7,7}) of minimal and maximal 7 characters.

Upvotes: 2

Sandeep Vaid
Sandeep Vaid

Reputation: 1459

Need to match with regular expression with whitespace character one or more times i.e. "\s"

String input = "  08/14       1351 XMGYV4      AOUSC             LTC                        .000          .000 VDPJU01PMP 11AUG14:15:17:05.99     ";
String[] split = input.split("\\s+");
System.out.println(Arrays.toString(split));

Upvotes: 0

Related Questions