A ^ or $ in a regular expression applies only to the first or last alternative, not to all of them

tx0/kotlin:regex-anchor-binds-one-alternativestrictwarningreliability/strings-and-regexdepth fastbug

What it finds

^yes|no$ reads as (^yes)|(no$): | binds more loosely than anything else, so the ^ belongs to the first alternative only and the $ to the last. A string that contains no anywhere before its end, or starts with yes, matches. The anchors were meant for the whole choice, as in ^(yes|no)$.

Reported is a pattern whose top level is a choice of alternatives, when the first one starts with ^ or the last one ends with $ but not all of them do.

From the rule's source, regex_patterns.rs.

Example from the rule's tests
val answer = Regex("^yes|no")tx0 reports: ^ applies to one alternative onlyval ending = Regex("yes|no$")tx0 reports: $ applies to one alternative onlyval fine = Regex("^(yes|no)$")val both = Regex("^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 strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:regex-anchor-binds-one-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/kotlin:regex-anchor-binds-one-alternative] reason="..."

tx0 explain tx0/kotlin:regex-anchor-binds-one-alternative shows the same in the terminal. Found a false positive? Report it.