Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to match words in a string that are wrapped in curly brackets using RegEx with Java

1 Answer

0 votes
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;

public class CurlyBracketMatcher {
    public static void main(String[] args) {
        String input = "This is a {string} with {multiple} {words} wrapped in curly brackets.";

        List<String> matches = extractWordsInCurlyBrackets(input);
        
        System.out.println("Matches: " + matches);
        System.out.println("Total Count: " + matches.size());
    }

    public static List<String> extractWordsInCurlyBrackets(String input) {
        // Define the RegEx pattern to match text in curly brackets
        String regex = "\\{([^}]+)\\}";

        // Compile the pattern
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        // List to store the matches
        List<String> matches = new ArrayList<>();

        // Find matches and add the captured group to the list
        while (matcher.find()) {
            matches.add(matcher.group(1)); // group(1) contains the text inside the brackets
        }

        return matches;
    }
}



/*
run:

Matches: [string, multiple, words]
Total Count: 3

*/

 



answered Mar 18, 2025 by avibootz
...