简体   繁体   English

Java正则表达式模式匹配长度

[英]Java regex pattern matching length

I have input string as 我输入的字符串为

input = "AAA10.50.30.20"

input.replaceAll("10.([01]?\\d\\d?|2[0-4]\\d|25[0-5]).([01]?\\d\\d?|2[0-4]\\d|25[0-5]).([01]?\\d\\d?|2[0-4]\\d|25[0-5])",
                        "X");

output is : "AAAX" 输出为: "AAAX"

However i want the output as "AAAXXXXXXXXXXX" 但是我希望输出为"AAAXXXXXXXXXXX"

It should replace the IP with multiple 'X' which are equivalent to number of characters in IP address 它应将IP替换为多个'X' ,这相当于IP地址中的字符数

If you just want to replace all digits and dots by X call str.replaceAll("\\\\d|\\\\.", "X") . 如果只想用X替换所有数字和点,则调用str.replaceAll("\\\\d|\\\\.", "X") If you want to match the exact pattern use something like 如果要匹配确切的模式,请使用类似

str.replaceAll("(?:\\d{1,3}\\.){3}\\d{1,3}", "X")
String input =  "AAA10.50.30.20";
Pattern p = p = Pattern.compile("10.([01]?\\d\\d?|2[0-4]\\d|25[0-5]).([01]?\\d\\d?|2[0-4]\\d|25[0-5]).([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
Matcher m = p.matcher(input);
String result = input;
while(m.find()){
    char[] replacement = new char[m.end()-m.start()];
    Arrays.fill(replacement, 'X');
    result = result.substring(0, m.start())
        + new String(replacement)
        + result.substring(m.end());
}
return result;

The problem is that you search for the IP-address with your regex. 问题是您用正则表达式搜索IP地址。 That gives you 1 match - the IP-address. 这给您1个匹配项-IP地址。 You then replace it with X, giving you AAAX. 然后,将其替换为X,从而获得AAAX。 How about fetching the string matched by the regex instead, then replacing all digits with X? 如何获取正则表达式匹配的字符串,然后将所有数字替换为X呢?

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

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