1

I would like to parse this string:

{HHH { AAAA } fS } SFS}

to get output by parenthesis number. If i want to get first the output should be :

HHH { AAAA 

when second :

HHH { AAAA } fS 

etc.

I tried this regex but it didn't give me expected results :

\{(.*?)\}{1}
YCF_L
  • 49,027
  • 13
  • 75
  • 115
Kmopsuy
  • 63
  • 2
  • 8
  • 2
    It's not something you can easily do with regex. You need to parse your string and find matching brackets. See https://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets – BackSlash Mar 18 '18 at 12:38
  • 1
    And what makes you think you want to use regex? – Joe C Mar 18 '18 at 12:40
  • I just wanted to ask if it is possible with regex. What a shame it isnt. ahh so thanks. I will try to parse it as BlackSlash said. Thanks – Kmopsuy Mar 18 '18 at 12:45
  • Finally I needed both soultions :D BlackSlash one and YCF_L. Thanks again – Kmopsuy Mar 22 '18 at 14:47

1 Answers1

2

You can solve your problem in inverse mode :

public String getResult(String text) {

    Pattern pattern = Pattern.compile("(\\{.*)\\}");
    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        return matcher.group(1);
    } else {
        return null;
    }
}

public static void main(String args[]) {
    Mcve mcve = new Mcve();
    String text = "{HHH { AAAA } fS } SFS}";

    while ((text = mcve.getResult(text)) != null) {
        System.out.println(text);
    }
}

Output

{HHH { AAAA } fS } SFS
{HHH { AAAA } fS 
{HHH { AAAA 

The idea is to get the first result then send this result to the same method until the method return null for example :

  • Send this String {HHH { AAAA } fS } SFS} receive {HHH { AAAA } fS } SFS
  • Send the result of the previous Iteration {HHH { AAAA } fS } SFS receive {HHH { AAAA } fS
  • Send the result of the previous Iteration {HHH { AAAA } fS receive {HHH { AAAA
  • Send the result of the previous Iteration {HHH { AAAA receive null now STOP
YCF_L
  • 49,027
  • 13
  • 75
  • 115