java

How to Extract Text Between Parenthesis in Java

In this tutorial, we are going to see how to extract text between parentheses or square brackets in Java. Regular Expressions or Regex is an API for defining patterns that can be used to find, manipulate, and edit a string in Java. Regex is widely used to define constraints. Regular expressions are provided under java.util package.
 

Extract Text Between Parenthesis using Pattern.compile():
import java.util.regex.*;

public class Main 
{
    public static void main(String[]args) 
    {
        String str = "Welcome to (StackHowTo)";
        Matcher m = Pattern.compile("\\((.*?)\\)").matcher(str);
      
        while(m.find()) 
        {
            System.out.println(m.group(1));
        }
    }
}

Output:

StackHowTo

 

 

Explanation:
  • .*? Matches any character between parentheses. ? after * tells the regex engine to make the shortest match.
  • To get text between square brackets, just replace the parentheses with square brackets as follows: compile ("\\[(.*?)\\]")

 

Extract Text Between Parenthesis using String.substring():
import java.util.regex.*;

public class Main 
{
    public static void main(String[]args) 
    {
        String str = "Welcome to (StackHowTo)";
        String res = str.substring(str.indexOf("(")+1,str.indexOf(")"));
        System.out.println(res);
    }
}

Output:

StackHowTo

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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