Finding tokens in a Java String

java, string

Solution

I think you can use the Apache Commons Lang feature that exists in StringUtils:

substringsBetween(java.lang.String str,
                  java.lang.String open,
                  java.lang.String close)

The API docs say it:

Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.

The Commons Lang substringsBetween API can be found here:

http://commons.apache.org/lang/apidocs/org/apache/commons/lang/StringUtils.html#substringsBetween(java.lang.String,%20java.lang.String,%20java.lang.String)

Problem

Is there a nice way to extract tokens that start with a pre-defined string and end with a pre-defined string? For example, let's say the starting string is "[" and the ending string is "]". If I have the following string: "hello[world]this[[is]me" The output should be: token[0] = "world" token[1] = "[is" (Note: the second token has a 'start' string in it)

Original source