2023-05-03 11:06:20 +02:00
== Why is this an issue?
2022-02-02 14:10:58 +01:00
include::../description.adoc[]
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2022-02-04 17:28:24 +01:00
[source,php]
2022-02-02 14:10:58 +01:00
----
preg_match("/Jack|Peter|/", "John"); // Noncompliant - returns 1
preg_match("/Jack||Peter/", "John"); // Noncompliant - returns 1
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2022-02-04 17:28:24 +01:00
[source,php]
2022-02-02 14:10:58 +01:00
----
preg_match("/Jack|Peter/", "John"); // returns 0
----
2023-05-03 11:06:20 +02:00
=== Exceptions
2022-02-02 14:10:58 +01:00
2023-01-11 14:32:28 +02:00
One could use an empty alternation to make a regular expression group optional. Note that the empty alternation should be the first or the last within the group, or else the rule will still report.
2022-02-02 14:10:58 +01:00
2022-02-08 11:35:42 +01:00
[source,php]
2022-02-02 14:10:58 +01:00
----
2023-01-11 14:32:28 +02:00
preg_match("/mandatory(|-optional)/", "mandatory"); // returns 1
2022-02-02 14:10:58 +01:00
preg_match("/mandatory(-optional|)/", "mandatory-optional"); // returns 1
----
2022-02-08 11:35:42 +01:00
However, if there is a quantifier after the group the issue will be reported as using both `|` and quantifier is redundant.
[source,php]
----
preg_match("/mandatory(-optional|)?/", "mandatory-optional"); // Noncompliant - using both `|` inside the group and `?` for the group.
----
2022-03-29 09:51:20 +02:00
include::../implementation.adoc[]