简体   繁体   中英

Java regex for matching curly braces and brackets within braces

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?

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM