0

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

1
  • "I have requirement to mask ip-address that starts with 10." - you said something like that on a deleted answer - I suggest you add that to your question. Commented Jul 7, 2014 at 10:12

3 Answers 3

1
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;
Sign up to request clarification or add additional context in comments.

1 Comment

Implementation of my answer =D
1

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")

2 Comments

Can you give me regex that matches 10.* ?
10\\..*. But could you take a look on regex syntax? It is not a big deal, believe me. People will be much more motivated to answer your questions if you can show some efforts you performed before asking the question.
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.