Home > Software engineering >  Java regex for matching curly braces and brackets within braces
Java regex for matching curly braces and brackets within braces

Time:08-18

I have the following String - There are {num} scores {/game/[game_name]/game_in}. I want to extract num and game_name from the string. I have the following Pattern - "\\{([^}] )}" which extract num from the String. How can I extend it to extract game_name also?

CodePudding user response:

In Java, you can use this regex and code:

String s = "{num} scores {/game/[game_name]/game_in}";
Pattern p = Pattern.compile(
                 "\\{([^]\\[\\{\\}] )\\}.*?\\[([^]\\[\\{\\}] )]");

List<String> res = p.matcher(s)
   .results()
   .flatMap(mr -> IntStream.rangeClosed(1, mr.groupCount())
   .mapToObj(mr::group))
   .collect(Collectors.toList());
//=> [num, game_name]

RegEx Demo

RegEx Details:

  • \{: Match {
  • ([^]\[{}] ): Capture group #1 to capture 1 of any char that is not {, }, [, ]
  • }: Match }
  • .*?: Match any text (lazy)
  • \[: Match [
  • ([^]\[{}] ): Capture group #2 to capture 1 of any char that is not {, }, [, ]
  • ]: Match ]
  • Related