Regular expression alternatives that are prefixes should be placed in proper order

  • MISPLACED_ALTERNATIVE_IN_REGEXP
  • Error
  • Medium
  • No tags

This rule applies when an alternative that is a prefix of another alternative is placed incorrectly in a regular expression.

Regular expression alternatives are tried sequentially from the left to the right. If the whole match succeeds with an alternative, later alternatives are not tried even when they can match further in the input string.

So, when a regular expression ends with alternatives or the remaining patterns after alternatives are all optional, an alternative that is a prefix should be placed after the longer one that contains the prefix. Otherwise, the longer one will never be selected.

Noncompliant Code Example

View with compliant examples side by side
// Example 1
let lines = text.split(/\r|\r\n|\n/); // MISPLACED_ALTERNATIVE_IN_REGEXP alarm because '\r' is a prefix of '\r\n'.

// Example 2
let normalized = text.replace(/inf|infinity/g, 'Infinity'); // MISPLACED_ALTERNATIVE_IN_REGEXP alarm because 'inf' is a prefix of 'infinity'.

Compliant Code Example

View with noncompliant examples side by side
// Example 1
let lines = text.split(/\r\n|\r|\n/);

// Example 2
let normalized = text.replace(/infinity|inf/g, 'Infinity');

Version

This rule was introduced in DeepScan 1.44.0.

See

Was this documentation helpful?