java:S5860 Usage of named groups is missed if Pattern is defined a static variable

Please provide

  • Operating system: RHEL 8.5
  • SonarLint plugin version: 5.0.1.33703
  • Programming language you’re coding in: Java 17
  • Is connected mode used:
    • Connected to SonarQube (and which version): 9.9.0.65466

And a thorough description of the problem / question:

SonarLint detects java:S5860 in the following but it should not:

public record BaseImageDeclaration(String domain, String path, String version, String alias) {

    private static final Pattern DECLARATION_PATTERN = Pattern.compile("^((?i)FROM) (?<domain>[^/]+)/(?<path>[^:\\s]+)(:(?<version>\\S*))?( ((?i)AS) (?<alias>\\S*))?");

    public static BaseImageDeclaration createFrom(String declaration) throws MojoExecutionException {
        final var imageMatcher = DECLARATION_PATTERN.matcher(declaration);
        if (imageMatcher.matches()) {
            final var domain = imageMatcher.group("domain");
            final var path = imageMatcher.group("path");
            final var version = imageMatcher.group("version");
            final var alias = imageMatcher.group("alias");
            return new BaseImageDeclaration(
                    domain,
                    path,
                    version == null ? "" : version,
                    alias == null ? "" : alias);
        }
        throw new MojoExecutionException(MessageFormat.format("\"{0}\" does not match the pattern {1}", declaration, DECLARATION_PATTERN));
    }
}

A slight modification makes the code compliant, showing the previous code really was fine too:

public record BaseImageDeclaration(String domain, String path, String version, String alias) {

    public static BaseImageDeclaration createFrom(String declaration) throws MojoExecutionException {
        final var declarationPattern = Pattern.compile("^((?i)FROM) (?<domain>[^/]+)/(?<path>[^:\\s]+)(:(?<version>\\S*))?( ((?i)AS) (?<alias>\\S*))?");
        final var imageMatcher = declarationPattern.matcher(declaration);
        if (imageMatcher.matches()) {
            final var domain = imageMatcher.group("domain");
            final var path = imageMatcher.group("path");
            final var version = imageMatcher.group("version");
            final var alias = imageMatcher.group("alias");
            return new BaseImageDeclaration(
                    domain,
                    path,
                    version == null ? "" : version,
                    alias == null ? "" : alias);
        }
        throw new MojoExecutionException(MessageFormat.format("\"{0}\" does not match the pattern {1}", declaration, declarationPattern));
    }
}

Hi @Adrien_Horgnies,
Thanks for reporting this issue and providing an example. Unfortunately, I am not able to reproduce the issue with your example.

A few questions to clarify:

  • Do you see the same issue on SonarQube?
  • What IDE are you using SonarLint in? Is it the latest version for that IDE?

Cheers,

Dorian