【问题标题】:Java regex mask all elements in a specific list in stringJava regex 屏蔽字符串中特定列表中的所有元素
【发布时间】:2022-04-12 08:03:40
【问题描述】:

我有一个从 JSON 对象转换而来的字符串。

  String myString =   { 
      \"name\":\"Dennis", 
      \"password\":\"12345\",
      \"secretValue\":\"12345\",
      \"OtherSecretList\":[\"ADD\",\"BND\"],
      \"TypeList\":[\"M\",\"F\"] 
    }

我想在记录之前屏蔽一些值。

String result = myString.replaceAll("(?<=secretValue\":\")(.*?)(?=\")", "*****")
                        .replaceAll("(?<=password\":\")(.*?)(?=\")", "*****");

这适用于非数组值。但我也想屏蔽 OtherSecretList 元素。

我试过这个答案

java regex mask all elements in a list with last 4 characters visible

我想看到像这样的价值

OtherSecretList:["****","****"]

但是失败了。任何帮助表示赞赏。

【问题讨论】:

  • 这里最简单的做法是使用 GSON 之类的东西解析原始 JSON 字符串,屏蔽您想要的内容,然后转换回字符串。

标签: java json regex masking data-masking


【解决方案1】:

你可以看看这个正则表达式。 https://regex101.com/r/WdWpgx/3

请注意,此解决方案仅适用于 json 文件小于 10000 的情况。由于 java lookbehind 不支持完整的正则表达式,它只允许有限的大小。

(?<=OtherSecretList\":\[.{0,10000}?\") # Match the secret list position. And assume that they are in the same line. Then match their own quote position.
(\w*(?=\w{4}\")|[A-Z]*(?=\w*\")) # If character longer than 4, then match as much as possible until only four left; otherwise, mask all to the another double quotation.

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 2021-04-02
    • 2015-06-29
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2022-10-19
    • 2014-09-14
    相关资源
    最近更新 更多