我想对一个字符串执行多个操作。我需要获得一个字符串并使用分隔符(";")提取不同的子字符串,然后再使用分隔符(":")提取不同的子字符串,如果字段匹配,则更新字段,最后用原始状态将它们连接起来,以便:firstName:Saroj;email:saroj@gmail.com;eaOldId;city:;center:com.test.Center::0/69将变为:firstName:xxxxxx;email:xxxxx@xxxx.com;eaOldId;city:;center:com.test.Center::0/69。
这个问题的基本需求是,我需要在“firstName”、“email”中修改一些必需的字段,以“xxxxxx”、“xxxxx@xxx.com”。我想加密敏感数据。
我在主修课上尝试了下面的传统方法
String shortData = "firstName:Saroj;email:saroj@gmail.com;eaOldId;city:;center:com.test.Center::0/69";
Map<String, List<String>> props = getProperties();
if(props.get("modelClasses").contains("com.test.Member")) {
List<String> modelFields = props.get(getModelClass());
List<String> shortDta = Stream.of(shortData.split(";")).map (elem -> new String(elem)).collect(Collectors.toList());
StringBuilder sb = new StringBuilder();
for(String data : shortDta){
String[] dta = data.split(":");
if(dta.length>2){
dta = data.split("=", 2);
}
if(dta.length == 1){
sb.append(data).append(";");
continue;
}
String key = dta[0];
if(modelFields.stream().anyMatch(d -> d.equalsIgnoreCase(key))){
String email = props.get("email").toString().replace("[", "").replace("]", "");
String pattern = props.get("commonPattern").toString().replace("[", "").replace("]", "");
sb.append(dta[0]).append(":").append(dta[0].equals("email") ? email : pattern).append(";");
} else {
sb.append(dta[0]).append(":;");
}
}
if (sb.length() > 0) {
sb.delete(sb.length() - 1, sb.length());
}下面是我从属性文件获得的数据--在这里手动转换为必需的对象
private Map<String, List<String>> getProperties(){
Map<String, List<String>> props = new HashMap<>();
List<String> str1 = new ArrayList<>();
str1.add("firstName");
str1.add("email");
List<String> str2 = new ArrayList<>();
str2.add("com.test.Member");
str2.add("com.test.Contact");
props.put("modelClasses", str2);
props.put("com.test.Member", str1);
props.put("com.test.Contact", str1);
props.put("commonPattern", Arrays.asList("xxxxxxx"));
props.put("email", Arrays.asList("xxxx@xxxx.com"));
return props;
}如果您注意到字符串中存在多个center:com.test.Center::0/69,比如,那么我也需要注意这一点。
我可以使用Java 8流做同样的事情吗?任何帮助高度appreciated.Thanks!
发布于 2019-10-26 07:28:00
我可以在这里使用String#replaceAll作为正则表达式一行选项:
String input = "firstName:Saroj;email:saroj@gmail.com;eaOldId;city:;center:com.test.Center::0/69";
System.out.println(input);
input = input.replaceAll("(?<=\\bfirstName:)[^;]+", "xxxxxx");
input = input.replaceAll("(?<=\\bemail:)[^@]+@[^;]+(\\.[^;]+)", "xxxxx@xxx$1");
System.out.println(input);这些指纹:
firstName:Saroj;email:saroj@gmail.com;eaOldId;city:;center:com.test.Center::0/69
firstName:xxxxxx;email:xxxxx@xxx.com;eaOldId;city:;center:com.test.Center::0/69注意:我可能建议完全屏蔽电子邮件,即使用xxxxx@xxx.xxx,以避免泄露任何关于用户真实电子邮件地址的信息。通过显示域和/或子域之类的内容,您可能更容易发现这些信息。
https://stackoverflow.com/questions/58568825
复制相似问题