简体   繁体   English

Java 正则表达式 - 否则条件

[英]Java Regex - if else condition

I have two strings.我有两个字符串。

String str1 = "\"password\":\"123456\", \"code\":\"434343\"";

I want to convert str1 to "\"password\":\"******\", \"code\":\"434343\""我想将 str1 转换为"\"password\":\"******\", \"code\":\"434343\""

String str2 = "\"password\":null, \"code\":\"434343\"";

and str2 to "\"password\":null, \"code\":\"434343\""和 str2 到"\"password\":null, \"code\":\"434343\""

I have to do this with only one regex.我必须只用一个正则表达式来做到这一点。 I read that Java does not support conditions in the regex.我读到 Java 不支持正则表达式中的条件。 But I see things like (?(?=regex)then|else)但我看到类似(?(?=regex)then|else)

I also tried so many things such that:我还尝试了很多事情,例如:

((?<=(?i)(password\"\\s*:\\s*\"*)).+?(?=\\",))|((?<!(password\"\\s*:\\s*))\\d+)

I use replaceAll() function with replacement parameter: "$1******"我使用 replaceAll() function 替换参数: "$1******"

If there is a "password":" , the value till \", should be asterisks.如果有"password":" ,直到\"的值应该是星号。 Otherwise, it remains as it is.否则,它保持原样。

I failed.我失败了。 Can anyone help me?谁能帮我?

If your starting string be a fragment from JSON, then you should parse it, and replace the password field with some masked version.如果您的起始字符串是来自 JSON 的片段,那么您应该解析它,并将密码字段替换为一些掩码版本。 If you must use regex, I suggest keeping it simple and using:如果您必须使用正则表达式,我建议保持简单并使用:

String str1 = "\"password\":\"123456\", \"code\":\"434343\"";
String output = str1.replaceAll("\"password\":\".*?\"", "\"password\":\"*****\"");
System.out.println(output);  // "password":"*****", "code":"434343"

I suggest not displaying the original password with every character replaced with an asterisk.我建议不要用星号替换每个字符来显示原始密码。 The reason for this is that it still gives away the original password's length, and therefore is not really fully masked.这样做的原因是它仍然泄露了原始密码的长度,因此并没有真正完全屏蔽。

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

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