rspec/rules/S6019/java/rule.adoc

38 lines
1.3 KiB
Plaintext
Raw Normal View History

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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
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
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
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)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]