How to solve SonarQube complaints about my code?

Viewed 537

I'd like to know how to get rid of all non-alphabet in a string please.

I have a String s, where many non-alphabetical characters can be inside. For instance, space, dots, slashes, and any other crazy stuff that are not from a, b, c ... z and not from A, B, C ... Z.

I just want to retain those a, b, c ... z and A, B, C ... Z.

Hence, I wrote:

private static String getGoodString(String s) {
    return s.replaceAll("[^a-zA-Z]", "");
}

This is actually working, quite happy.

However, SonarQube is complaining with:

Refactor this code to use a "static final" Pattern.

Replace these character ranges with Unicode-aware character classes.

How may I achieve the same (get ride of any non-alphabet), while making SonarQube very happy at the same time please?

2 Answers

Try using this version:

// inside your class
private static final Pattern p = Pattern.compile("[^\\p{Alpha}]");

private static String getGoodString(String s) {
    return p.matcher(s).replaceAll("");
}

Here I am using a static final Pattern. Also, the regex \p{Alpha} is the Unicode version for matching any letter character.

Change to

private static final Pattern regexPattern = Pattern.compile("[^\\p{Alpha}]", Pattern.CASE_INSENSITIVE);

private static String getGoodString(String s) {
    return regexPattern.matcher(s).replaceAll("");
}
package com.company;

import java.util.regex.Pattern;

public class Main {

    private static final Pattern regexPattern = Pattern.compile("[^\\p{Alpha}]", Pattern.CASE_INSENSITIVE);

    public static void main(String[] args) {
        String myPreferString = getGoodString("d35545.343\343C3.~&%@#43x");
        System.out.println("My prefer string: " + myPreferString);

        String myPreferStringOld = getGoodStringOld("d35545.343\343C3.~&%@#43x");
        System.out.println("My prefer string (oldway): " + myPreferStringOld);
    }

    private static String getGoodString(String s) {
        return regexPattern.matcher(s).replaceAll("");
    }

    private static String getGoodStringOld(String s) {
        return s.replaceAll("[^a-zA-Z]", "");
    }
}

(1) https://rules.sonarsource.com/java/RSPEC-5867

Unicode-aware versions of character classes should be preferred

(2) https://rules.sonarsource.com/java/tag/regex/RSPEC-4248

Regex patterns should not be created needlessly

(3) Javadoc

/**
 * Enables case-insensitive matching.
 *
 * <p> By default, case-insensitive matching assumes that only characters
 * in the US-ASCII charset are being matched.  Unicode-aware
 * case-insensitive matching can be enabled by specifying the {@link
 * #UNICODE_CASE} flag in conjunction with this flag.
 *
 * <p> Case-insensitive matching can also be enabled via the embedded flag
 * expression&nbsp;{@code (?i)}.
 *
 * <p> Specifying this flag may impose a slight performance penalty.  </p>
 */
public static final int CASE_INSENSITIVE = 0x02;

enter image description here

Related