0

How do I get a string which is between paranthesis using a regular expression in JAVA? Eg: if I have a string abc(de)gh Then I want the "de" Substing.

Toto
  • 89,455
  • 62
  • 89
  • 125
Tirth Trivedi
  • 155
  • 1
  • 6

2 Answers2

1

Regex: \((?<TEXT>[^()]+)\) or (?<=\()[^()]+(?=\))

Details:

\( matches the character (

(?<TEXT>) Named Capture Group TEXT

[^()]+ Match a single characteras not present in the list

+ Matches between one and unlimited times

\) matches the character )

Regex demo

Srdjan M.
  • 3,310
  • 3
  • 13
  • 34
0

Try this

public void test1() {

    String str = "abc(de)gh(il)jk";
    String regex = "\\((.*?)\\)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        System.out.println(matcher.group(1)); 
    }

}
fanfanta
  • 181
  • 14