0

I have below string

My string {inside bracket} then again some other text {inside the bracket}

I am writing regEx to get the text between {} there could be n number of curly bracket blocks

below is the apex code I wrote

    // Instantiate a new Pattern object "patternInBrackets"
    Pattern patternInBrackets = Pattern.compile('\\{(.*?)\\}');

    // Then instantiate a new Matcher object "MyMatcher"
    Matcher summaryQueryMatcher = patternInBrackets.matcher(summaryQuery);

    system.debug(summaryQueryMatcher.group());

I throw an error saying no match found for the above string, could someone please suggest what am I doing wrong?

1 Answer 1

2

You have to find() a match first:

String summaryQuery = 'My string {inside bracket} then again some other text {inside the bracket}';
Pattern patternInBrackets = Pattern.compile('\\{(.*?)\\}');
Matcher summaryQueryMatcher = patternInBrackets.matcher(summaryQuery);
while(summaryQueryMatcher.find()) { // returns false when no more matches
    system.debug(summaryQueryMatcher.group());
    system.debug(summaryQueryMatcher.group(1)); // just the text between the brackets      
}
2
  • Thank you so much for your help, but it returned only 2nd match, didn't print the first match like expected is "inside bracket" and 2nd is "inside the bracket" it printed only 2nd one, would you please suggest?
    – gs650x
    Commented Jul 22, 2021 at 8:32
  • @gs650x You might be misreading the logs. That is the exact code I used in my org to verify it works.
    – sfdcfox
    Commented Jul 22, 2021 at 8:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .