What does Repetition range replaceable by '*' mean?

Viewed 694

I performed code analyzer in IntelliJ IDEA and it shows weak warning as

Repetition range replaceable by '*'

Its shows warning on below line of code Where I'm using regex pattern

String pattern = prefix + ".{" + length + "}" + suffix;

I'm not sure whether my code will work after replace .{ with *

Simplified version of code :

String code = "AUTONARNDATEST";

String prefix = "AUTO";
String suffix = "TEST";
String length = "6";
String pattern = prefix + ".{" + length + "}" + suffix;

if(code.matches(pattern)) {
    System.out.println("thumbs_up");
}else {
    System.out.println("thumbs_down");
}

Can anyone please help.

1 Answers

The problem is caused by analyzer in Intellij IDEA. This is the relevant part:

  @Override
  public void visitRegExpQuantifier(RegExpQuantifier quantifier) {
    if (quantifier.isCounted()) {
      final RegExpNumber minElement = quantifier.getMin();
      final String min = minElement == null ? "" : minElement.getText();
      final RegExpNumber maxElement = quantifier.getMax();
      final String max = maxElement == null ? "" : maxElement.getText();
      if (!max.isEmpty() && max.equals(min)) {
         ...........
      }
      else if (("0".equals(min) || min.isEmpty()) && "1".equals(max)) {
         ..........
      }
      else if (("0".equals(min) || min.isEmpty()) && max.isEmpty()) {
        myHolder.newAnnotation(HighlightSeverity.WEAK_WARNING, RegExpBundle.message("weak.warning.repetition.range.replaceable.by.0", "*"))
        .withFix(new SimplifyQuantifierAction(quantifier, "*")).create();
      }
       ...........

In this case it sees the string .{, and interprets it as a quantifier with both min and max ranges empty, because it cannot statically parse the content of length and minElement/maxElement.getText() return null. So it falls to the branch which produces the warning. If IDEA can statically parse length, then the warning does not come:

String length = "6";
String pattern = ".{" + length + "}";  // No warning
if ("a".matches(pattern)) ;

Compare with:

String length = new Scanner(System.in).nextLine();
String pattern = ".{" + length + "}";  // Warning, cannot statically parse length
if ("a".matches(pattern)) ;

As I mentioned in the comment you can avoid it if you produce the pattern with String.format:

String pattern = String.format("%s.{%s}%s", prefix, length, suffix);
Related