What is StringUtils.substringsBetween() in Java?

The StringUtils.substringsBetween() the method provided by the Apache Commons Lang library is used to extract multiple substrings from the larger string. It returns an array of the substrings that lie between two specified delimiters.

Note: Add the org.apache.commons.lang3 library to Project.

Syntax for StringUtils.substringsBetween()

public static String[] substringsBetween(String str, String open, String close)

Parameters:

  • str: input string from which to extract substrings.
  • open: starting delimiter of the substrings.
  • close: ending delimiter of the substrings.

Return Value: An array of the substrings that are located between the specified opening and closing delimiters.

Examples of substringsBetween()

Example 1:

In this example, we will print the substrings present between {}

Java




// Java program to separate substrings between()
  
import java.io.*;
import org.apache.commons.lang3.StringUtils;
  
// Driver class
public class MyClass {
  
    // Main method
    public static void main(String[] args){
  
        // Define the input string containing placeholders
        String input
            = "Hello {world}, How {are} you {doing} today?";
  
        // Extract all substrings between curly braces using
        // StringUtils library
        String[] substrings = StringUtils.substringsBetween(
            input, "{", "}");
  
        // Loop through each extracted substring and print
        // it
        for (String substring : substrings) {
            System.out.println("Extracted substring: "
                               + substring);
        }
    }
}


Output :

world
are
doing

Example 2:

In this example, we will print the substrings present between []

Java




// Java program to separate substrings between()
import java.io.*;
import org.apache.commons.lang3.StringUtils;
  
//Driver class
public class MyClass {
  
      //Main method
    public static void main(String[] args) {
  
        // Define the input string containing bracketed words
        String input = "The [quick] [brown] [fox] jumps over the [lazy] [dog]";
  
        // Extract all bracketed words using StringUtils library
        String[] substrings = StringUtils.substringsBetween(input, "[", "]");
  
        // Loop through each extracted word and print it
        for (String substring : substrings) {
            System.out.println("Extracted word: " + substring);
        }
    }
}


Output :

quick
brown
fox
lazy
dog

Note: Alternatively, you can use String[] substrings = input.split(“\\{([^}]+)\\}”); to get the array of substrings between the delimiters.



Contact Us