What is StringUtils.substringsBetween() in Java?
Last Updated :
28 Dec, 2023
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
import java.io.*;
import org.apache.commons.lang3.StringUtils;
public class MyClass {
public static void main(String[] args){
String input
= "Hello {world}, How {are} you {doing} today?" ;
String[] substrings = StringUtils.substringsBetween(
input, "{" , "}" );
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
import java.io.*;
import org.apache.commons.lang3.StringUtils;
public class MyClass {
public static void main(String[] args) {
String input = "The [quick] [brown] [fox] jumps over the [lazy] [dog]" ;
String[] substrings = StringUtils.substringsBetween(input, "[" , "]" );
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.
Share your thoughts in the comments
Please Login to comment...