|| or a | at either end of a pattern adds a choice that matches nothing at all

tx0/python:regex-empty-alternativerecommendedwarningbug

What it finds

a||b and a pattern that starts or ends with | have an empty alternative, which matches the empty string everywhere: re.search("x|", s) finds a match in every string. Groups such as (a|), a common way to write an optional part, are left alone.

From the rule's source, regex_empty_alternative.rs.

Example from the rule's tests
import refrom re import match a = re.compile("cat||dog")tx0 reports: this pattern has an empty alternativeb = match("yes|", text)tx0 reports: this pattern has an empty alternativee = match("(yes|)", text)c = re.compile("|start")tx0 reports: this pattern has an empty alternatived = re.compile("(yes|no)?")
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:regex-empty-alternative" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:regex-empty-alternative] reason="..."

tx0 explain tx0/python:regex-empty-alternative shows the same in the terminal. Found a false positive? Report it.