javaregexstringreplace

How to replace word with special character from string in java?


I am writing a method that should replace all words which match with ones from the list with '****'.

So far, I have code that works fine with strings without special characters, but all string with special characters are ignoring.

Here's the code I have so far:

public static String maskKeywordData(String data, List<String> keywords) {
  for (String keyword: keywords) {
            String insensitiveWord = "(?i)\\b" + keyword + "\\b";
            data = data.replaceAll(insensitiveWord, StringUtils.repeat("*", keyword.length()));
        }
        return data;
    }

E.g. I have a list of keywords ['c.u.l.t', 'ba$$', 'witch'].

Input :

"Hello c.u.l.t with ba$$ and witch"

Expected output :

"Hello ******* with **** and *****"


Solution

  • You can use

    public static String maskKeywordData(String data, List<String> keywords) {
        for (String keyword : keywords) {
            String insensitiveWord = "(?i)\\b" + keyword;
            data = data.replaceAll(insensitiveWord, "*".repeat(keyword.length()));
        }
        return data;
    }
    

    Its only downside is, in the list, for $ you have to use\\$ in the word, like ba$$ will be ba\\$\\$ in the list for the above code to run.

    Reason is, \\b is word boundary which checks for (^ \w|\w $|\W \w|\w \W), due to which the word ba$$ is not taken.

    Output by the above code:

    Hello ******* with **** and *****