Search code examples
javaregexreplaceall

Java replaceAll with regex


I have this input from the user:

*.*.*.*

(* = censor) this string is an input from the user, that's what the user wants to censor. how do I convert it to regex? Edit: Let me explain again. user wants to censor anything in * between the dots, so he types in *.*.*.*, and I need to convert it to regex. he could type text*text too

I have tried doing:

String strLine = "93.38.31.43 and 39.53.19.33 and lala.lala.lala.lala";
String input = "*.*.*.*";
String replaceWord = "[censor]";
input = input.replaceAll("\\*","\\\\\\w+");
strLine = strLine.replaceAll("(?=\\s+)\\S*)" + input + "(?=\\s+)\\S*",replaceWord);

I tried replacing the * with \\w+ to get this output:

the ip's are [censor] and [censor] and [censor]

but It does not work, doesn't replace anything.

when I'm doing it like that, it works:

strLine = strLine.replaceAll("?<=\\s+)\\S*" +"\\w+\\.\\w+\\.\\w+\\.\\w+"+"(?\\s+)\\S*",replaceWord);

why doesn't it work? is there a better way doing it?


Solution

  • You can use:

    String strLine = "93.38.31.43 and 39.53.19.33 and lala.lala.lala.lala";
    String input = "*.*.*.*";
    String replaceWord = "[censor]";
    
    input = input.replace("*","\\w+").replace(".", "\\.");
    System.out.println(input); // \w+\.\w+\.\w+\.\w+
    
    strLine = strLine.replaceAll("\\b" + input + "\\b", replaceWord);
    System.out.println(strLine);
    //=> [censor] and [censor] and [censor]