rspec/rules/S6019/java/rule.adoc

46 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
"start123endstart456".replaceAll("start\\w*?(end)?", "x"); // Noncompliant. In contrast to what one would expect, the result is not "xx".
str.matches("\\d*?"); // Noncompliant. Matches the same as "\d*", but will backtrack in every position.
2021-04-28 16:49:39 +02:00
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
"start123endstart456".replaceAll("start\\w*?(end|$)", "x"); // Result is "xx".
str.matches("\\d*");
2021-04-28 16:49:39 +02:00
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Fix this reluctant quantifier that will only ever match the empty string.
=== Highlighting
The repetition
endif::env-github,rspecator-view[]