Reputation: 11
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
Reputation:
Perhaps consider Krayo's solution String[] array = s.split( "\\s+" );
?
Upvotes: 0
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
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