java 正则表达式重置捕获组

hpxqektj  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(97)

我尝试过使用“|'但似乎不可能首先解析Map(如果可能),如果不可能,则将值作为一个整体进行解析,但将捕获组保持为否1/2,尝试使用分支重置组,但也无法管理。欢迎提出任何建议。

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Scratch {

  public static void main(String[] args) {

    final Pattern outerKeyPattern = Pattern.compile("([A-Z]+)\\((.*)\\)", Pattern.MULTILINE);
    final Pattern innerPattern = Pattern.compile("([A-Z]+)\\((.*?)\\)");

    // There will always be a value in the outer, 
    // but sometimes it's an inner map, i.e only need to solve this case, no other exeptions
 
    String input = """
      VALUE(123)
      OUTERVALUE(INNERVALUE(123)OTHERVALUE(456))
      """;

    Map<String, Map<String, String>> outer = new HashMap<>();
    Matcher matcher = outerKeyPattern.matcher(input);
    while (matcher.find()) {
      String key = matcher.group(1);
      String value = matcher.group(2);
      Matcher valueMatcher = innerPattern.matcher(value);
      Map<String, String> innerMap = new HashMap<>();
      while (valueMatcher.find()) {
        innerMap.put(valueMatcher.group(1), valueMatcher.group(2));
      }
      outer.put(key, innerMap);
    }

    System.out.println(outer);
  }
}

产生输出:

{VALUE={}, OUTERVALUE={INNERVALUE=123, OTHERVALUE=456}}

我需要将value也解析为内部Map的key,它的值为null:

{VALUE={123=}, OUTERVALUE={INNERVALUE=123, OTHERVALUE=456}}
46qrfjad

46qrfjad1#

既然你看起来是逐行处理数据的,而且代码片段中的注解表明你的数据格式良好,你可以先提取外部大括号的全部内容,然后检查该值是否包含任何嵌套的键-值对。对你的正则表达式做一些修改,下面的内容可能就是你要寻找的:

public static void main(final String[] args) {

    Pattern outerPattern = Pattern.compile("([A-Z]+)\\((.*)\\)");
    Pattern innerPattern = Pattern.compile("([A-Z]+)\\(([^()]*)\\)");

    String input = """
            VALUE(123)
            OUTERVALUE(INNERVALUE(123)OTHERVALUE(456))
            """;

    Map<String, Map<String, String>> outer = new HashMap<>();

    input.lines().forEach(line -> {
        Matcher matcher = outerPattern.matcher(line);
        matcher.find();

        String key   = matcher.group(1);
        String value = matcher.group(2);

        Map<String, String> innerMap = new HashMap<>();

        if (!innerPattern.asPredicate().test(value)) {       //check if value doesn't contain any nested key-value-pairs
            innerMap.put(value, "");
        } else {
            Matcher valueMatcher = innerPattern.matcher(value);
            while (valueMatcher.find()) {
                innerMap.put(valueMatcher.group(1), valueMatcher.group(2));
            }
        }
        outer.put(key, innerMap);
    });

    System.out.println(outer);
}

相关问题