O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required