【问题标题】:Java - Remove keys matching regex from JsonObjectJava - 从 JsonObject 中删除匹配正则表达式的键
【发布时间】:2018-05-21 23:44:46
【问题描述】:

我可以使用以下方法从 JsonObject 中删除密钥:

String prop = "test";
JsonObject o = parser.parse(props).getAsJsonObject();
o.remove(prop);

我需要从 JsonObject 中删除与特定模式匹配的所有键,就像以“test.*”开头的任何内容一样。除了遍历键并找到匹配项之外,还有其他方法可以删除与给定模式匹配的键吗?

input: {"test":"0","test_1": "1","test_10":"10", "site":"abc.com"}
expected output: {"site":"abc.com"}

谢谢!

【问题讨论】:

  • 你能分享一个输入/输出的例子吗
  • 遍历键并检查contains您的测试字符串

标签: java json regex


【解决方案1】:

没有。

您可以做的最好的事情是在循环之前编译正则表达式以提高性能:

Pattern pattern = Pattern.compile(prop);
Iterator<Entry<...>> it = o.entrySet().iterator();
while (it.hasNext()) {
    Entry<...> entry = it.next();
    if (pattern.matcher(entry.getKey()).matches()) {
        i.remove();
    }
}

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多