SonarQube issue: Remove duplicates in this character class

I have implemented the regex expression to remove all the special characters with empty strings and remove space(if any), which is working fine in my code but sonarQUbe is complaining as this is non-compliant solution, Can anyone tell me how to fix this issue

String c = "test10101010test%79%% %%% $$$  \t \n $$$#$@^$%~`***c  33";
    Pattern pt = Pattern.compile("[\\W\\s+]");
    Matcher match= pt.matcher(c);
    while(match.find())
    {
        c=c.replaceAll("\\"+match.group(), "").toLowerCase();
    }
     System.out.println(c);

I am getting error at "[\\W\\s+]". Getting below error Remove duplicates in this character class.

Can anyone suggest how to fix this issue?


Your regex is a character class, [...]. It matches \W (chars other than letters, digits or connector punctuation (underscore in ASCII mode), \s (a whitespace) and a + char. The error you get is related to the fact that both + and whitespace chars can already be matched with \W.

So your pattern is basically \W. Note it does not match underscores that are punctuation chars. If you want to remove all chars other than alphanumeric chars use [\W_] or \P{Alnum} pattern.

More, you usually do not need to check for a match before replacing, the following should be enough:

c=c.replaceAll("\\W+", "").toLowerCase();
// or
c=c.replaceAll("[\\W_]+", "").toLowerCase();
// or
c=c.replaceAll("\\P{Alnum}+", "").toLowerCase();