Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-5994

Regex patterns following a possessive quantifier should not always fail

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Change this impossible to match sub-pattern that conflicts with the previous possessive quantifier.
    • Highlighting:
      Hide

      The conflicting sub-pattern after the possessive qualifier.

      Show
      The conflicting sub-pattern after the possessive qualifier.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      Possessive quantifiers in Regex patterns like below improve performance by eliminating needless backtracking:

      ?+ , *+ , ++ , {n}+ , {n,}+ , {n,m}+
      

      But because possessive quantifiers do not keep backtracking positions and never give back, the following sub-patterns should not match only similar characters. Otherwise, possessive quantifiers consume all characters that could have matched the following sub-patterns and nothing remains for the following sub-patterns.

      Noncompliant Code Example

      Pattern pattern1 = Pattern.compile("a++abc");       // Noncompliant, the second 'a' never matches
      Pattern pattern2 = Pattern.compile("\\d*+[02468]"); // Noncompliant, the sub-pattern "[02468]" never matches
      

      Compliant Solution

      Pattern pattern1 = Pattern.compile("aa++bc");            // Compliant, for example it can match "aaaabc"
      Pattern pattern2 = Pattern.compile("\\d*+(?<=[02468])"); // Compliant, for example it can match an even number like "1234"
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              alban.auzeill Alban Auzeill
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: