S5860 - Names of regular expressions named groups should be used (when they’re actually…)

With SonarQube Developer Edition Version 8.9.2 (build 46101) I get the S5860 for the following Java code:

  private static final Pattern TRAILING_NUMERATOR =
      Pattern.compile("^.*[^\\d]0*(?<numerator>\\d+)$");

  public static String trimTrailingNumerator(String text) {
    var str = text;
    var matcher = TRAILING_NUMERATOR.matcher(text);
    if (matcher.matches()) {
      str = str.substring(0, matcher.start("numerator"));
    }
    return str;
  }

IMHO the named group is used in line 8 of the sample. Maybe it is not recognized because the code don’t uses Matcher.group to retrieve the groups text.

Oh and don’t mind the security issue of the pattern. I’m on it.

Hey Kai!

Thanks a lot for the feedback and reproducer.
It seems we missed the methods start() and end() and indeed only considered group() when implementing the rule.

This will be fixed with this ticket: [SONARJAVA-4196] FP on S5860 when using methods matcher.start() and matcher.end() - SonarSource

Cheers,
Michael

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.