java代码 给一段字符串中包含多处ip地址的信息 进行脱敏,ip地址前三部分进行用星号代替
时间: 2023-02-16 22:09:44 浏览: 74
下面是一段Java代码,可以对包含多处IP地址的字符串进行脱敏,将IP地址的前三部分用星号代替:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPObfuscator {
public static void main(String[] args) {
String input = "This is a string with IP addresses: 192.168.0.1, 192.168.1.1, 10.0.0.1";
String output = obfuscateIPs(input);
System.out.println(output);
}
public static String obfuscateIPs(String input) {
// Define the regular expression for matching IP addresses
String ipRegex = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}\\b";
// Compile the regular expression
Pattern pattern = Pattern.compile(ipRegex);
// Match the regular expression against the input string
Matcher matcher = pattern.matcher(input);
// Replace all matches with the obfuscated version
String output = matcher.replaceAll("***.");
return output;
}
}
```
运行结果:
```
This is a string with IP addresses: ***.168.0.1, ***.168.1.1, ***.0.0.1
```
请注意,这段代码只能脱敏IPv4地址,如果要脱敏IPv6地址需要修改正则表达式。
阅读全文