How to Get String Between Two Characters in Java

In this post, we will see How to get String between two characters in java.

Ways to get String between two characters in java.

There are multiple ways to How to get String between two characters in java

Using String’s substring() method

To get String between two characters in java, use String’s substring() method.

  • Find index of first character in String.
  • Find index of second character in the String.
  • Use String’s substring() method to get String between these two indices.

String’s substring() method returns new String between start index(inclusive) and endIndex(Exclusive)

Here is syntax of substring method.

Here is an example:

Output:

String between ( ) is: Java blog

Using Apache common library

The apache foundation provides the apache-commons-lang jar. This jar contains a collection of utility classes, one of which is the StringUtils class. The StringUtils class contains a substringBetween() method that returns String between two passed Strings in Java.

Before we can use the methods in this jar, we need to add it our Build Path.
Here is the dependency which you need to add for Apache common lang3 in pom.xml.

Here is an example:

Output:

String between ( ) is: Java blog

Using Regex

You can also use regex incase you have more complex requirement.

We have specified regex to get String between ( and ). You need to change the regex based on the characters and use it your program,
Here is an example:

Output:

Java blog

That’s all about how to get String between two characters in java

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *