简体   繁体   中英

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"

However i want the output as "AAAXXXXXXXXXXX"

It should replace the IP with multiple 'X' which are equivalent to number of characters in IP address

If you just want to replace all digits and dots by X call 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. That gives you 1 match - the IP-address. You then replace it with X, giving you AAAX. How about fetching the string matched by the regex instead, then replacing all digits with X?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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