Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern to extract text between parenthesis

Tags:

java

regex

How to extract string from "(" and ")" using pattern matching or anything. For example if the text is

"Hello (Java)"

Then how to get only "Java"?

like image 805
Rajeev Sahu Avatar asked Jun 17 '14 05:06

Rajeev Sahu


People also ask

How do I extract text between parentheses in Excel?

Extract Text Between Parenthesis To extract the text between any characters, use a formula with the MID and FIND functions. The FIND Function locates the parenthesis and the MID Function returns the characters in between them.

How do I extract text between parentheses in Python?

The simplest way to extract the string between two parentheses is to use slicing and string. find() . First, find the indices of the first occurrences of the opening and closing parentheses. Second, use them as slice indices to get the substring between those indices like so: s[s.


2 Answers

Try this:

String x = "Hello (Java)"; Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x); while (m.find()) {     System.out.println(m.group(1)); } 

or

String str = "Hello (Java)"; String answer = str.substring(str.indexOf("(")+1, str.indexOf(")")); 
like image 131
Rahul Tripathi Avatar answered Oct 01 '22 12:10

Rahul Tripathi


List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile("\\((.*?)\\)"); Matcher regexMatcher = regex.matcher("Hello This is (Java) Not (.NET)");  while (regexMatcher.find()) {//Finds Matching Pattern in String    matchList.add(regexMatcher.group(1));//Fetching Group from String }  for(String str:matchList) {    System.out.println(str); } 

OUTPUT

Java .NET 

What does \\((.+?)\\) mean?

This regular Expression pattern will start from \\( which will match ( as it is reserved in regExp so we need escape this character,same thing for \\) and (.*?) will match any character zero or more time anything moreover in () considered as Group which we are finding.

like image 33
akash Avatar answered Oct 01 '22 12:10

akash