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

Regex lookahead assertions should not be contradictory

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove or fix this lookahead assertion that can never be true
    • Highlighting:
      Hide

      The lookahead assertion in question

      Show
      The lookahead assertion in question
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      Lookahead assertions are a regex feature that makes it possible to look ahead in the input without consuming it. It is often used at the end of regular expressions to make sure that substrings only match when they are followed by a specific pattern.

      However, they can also be used in the middle (or at the beginning) of a regex. In that case there is the possibility that what comes after the lookahead does not match the pattern inside the lookahead. This makes the lookahead impossible to match and is a sign that there's a mistake in the regular expression that should be fixed.

      Noncompliant Code Example

      Pattern.compile("(?=a)b"); // Noncompliant, the same character can't be equal to 'a' and 'b' at the same time
      

      Compliant Solution

      Pattern.compile("(?<=a)b");
      Pattern.compile("a(?=b)");
      

        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: