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

Reluctant quantifiers in regular expressions should be followed by an expression that can't match the empty string

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Fix this reluctant quantifier that will only ever match the empty string.
    • Highlighting:
      Hide

      The repetition

      Show
      The repetition
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      When a reluctant quantifier (such as *? or +?) is followed by a pattern that can match the empty string or directly by the end of the regex, it will always match the empty string when used with methods that find partial matches (such as find, replaceAll, split etc.).

      Similarly, when used with methods that find full matches, a reluctant quantifier that's followed directly by the end of the regex (or a pattern that always matches the empty string, such as ()) behaves indistinguishably from a greedy quantifier while being less efficient.

      This is likely a sign that the regex does not work as intended.

      Noncompliant Code Example

      str.split(".*?x?"); // Noncompliant, this will behave just like "x?"
      str.matches(".*?"); // Noncompliant, replace with ".*"
      

      Compliant Solution

      str.split(".*?x");
      str.matches(".*");
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              sebastian.hungerecker Sebastian Hungerecker
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: