简体   繁体   English

Java 正则表达式用于匹配花括号和大括号内的括号

[英]Java regex for matching curly braces and brackets within braces

I have the following String - There are {num} scores {/game/[game_name]/game_in} .我有以下字符串 - There are {num} scores {/game/[game_name]/game_in} I want to extract num and game_name from the string.我想从字符串中提取numgame_name I have the following Pattern - "\\{([^}]+)}" which extract num from the String.我有以下模式 - "\\{([^}]+)}"从字符串中提取num How can I extend it to extract game_name also?我怎样才能扩展它来提取game_name呢?

In Java, you can use this regex and code:在 Java 中,您可以使用此正则表达式和代码:

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 {, }, [, ] ([^]\[{}]+) :捕获组 #1 以捕获不是{, }, [, ]的任何字符的 1+
  • } : Match } } : 匹配}
  • .*? : Match any text (lazy) :匹配任何文本(惰性)
  • \[ : Match [ \[ : 匹配[
  • ([^]\[{}]+) : Capture group #2 to capture 1+ of any char that is not {, }, [, ] ([^]\[{}]+) :捕获组 #2 以捕获 1+ 的任何不是{, }, [, ]的字符
  • ] : Match ] ] : 匹配]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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