2.13. Parsing Formatted Strings

Problem

You need to parse a string containing control characters and the delimiters (, [, ), ], and ,.

Solution

Use variations of substring() from StringUtils. This next example parses a string that contains five numbers delimited by parentheses, brackets, and a pipe symbol (N0 * (N1,N2) [N3,N4] | N5):

String formatted = " 25 * (30,40) [50,60] | 30"

PrintWriter out = System.out;
out.print("N0: " + StringUtils.substringBeforeLast( formatted, "*" ) );
out.print(", N1: " + StringUtils.substringBetween( formatted, "(", "," ) );
out.print(", N2: " + StringUtils.substringBetween( formatted, ",", ")" ) );
out.print(", N3: " + StringUtils.substringBetween( formatted, "[", "," ) );
out.print(", N4: " + StringUtils.substringBetween( formatted, ",", "]" ) );
out.print(", N5: " + StringUtils.substringAfterLast( formatted, "|" ) );

This parses the formatted text and prints the following output:

N0: 25, N1: 30, N2: 40, N3: 50, N4: 60, N5: 30

Discussion

The following public static methods come in handy when trying to extract information from a formatted string:

StringUtils.substringBetween( )

Captures content between two strings

StringUtils.substringAfter( )

Captures content that occurs after the specified string

StringUtils.substringBefore( )

Captures content that occurs before a specified string

StringUtils.substringBeforeLast( )

Captures content after the last occurrence of a specified string

StringUtils.substringAfterLast( )

Captures content before the last occurrence ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.