Table of Contents
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.
1 2 3 |
public String substring(int startIndex, int endIndex) |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class GetStringBetweenTwoCharactersMain { public static void main(String[] args) { String str = "Java2blog(Java blog)"; String result = getStringBetweenTwoCharacters(str,"(",")"); System.out.println("String between ( ) is: "+result); } public static String getStringBetweenTwoCharacters(String input, String to, String from) { return input.substring(input.indexOf(to)+1, input.lastIndexOf(from)); } } |
Output:
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
.
1 2 3 4 5 6 7 |
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import org.apache.commons.lang3.StringUtils; public class GetStringBetweenTwoCharactersMainApache { public static void main(String[] args) { String str = "Java2blog(Java blog)"; String result = StringUtils.substringBetween(str,"(",")"); System.out.println("String between ( ) is: "+result); } } |
Output:
Further reading:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GetStringBetweenTwoCharactersMainRegex { public static void main(String[] args) { String str = "Java2blog(Java blog)"; // String between ( and ) Pattern p = Pattern.compile("\\(.*?\\)"); Matcher m = p.matcher(str); if(m.find()) System.out.println((m.group().subSequence(1, m.group().length()-1))); } } |
Output:
That’s all about how to get String between two characters in java