Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
272 changes: 272 additions & 0 deletions docs/content/rules/sort-regexp.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
---
title: sort-regexp
description: Keep regular expressions predictable by sorting flags, character classes, and alternation branches. This ESLint rule helps you avoid subtle regex bugs and improves readability
shortDescription: Enforce sorted regular expressions
keywords:
- eslint
- regex sorting
- regular expressions
- eslint rule
- code quality
- javascript linting
---

import CodeExample from '../../components/CodeExample.svelte'
import CodeTabs from '../../components/CodeTabs.svelte'
import dedent from 'dedent'

Enforce consistent ordering in regular expressions: flags, character-class elements, and alternation branches inside capture groups or the top-level pattern.

Large patterns become easier to maintain when related branches are grouped and repeatedly used flags or character classes follow the same order. This rule helps you spot missing alternatives, avoid duplicated work, and keeps refactors safer by applying one sorting strategy across your codebase.

The rule is **safe** – it only reorders elements without changing their meaning.

Comment on lines +22 to +23
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Docs overstate safety; add caveat and guidance

Reordering alternations is not universally safe (e.g., shared prefixes like (ab|a)), and numeric backreferences can also change behavior if group numbering shifts after reordering.

- The rule is **safe** – it only reorders elements without changing their meaning.
+ Important: Reordering can change behavior in specific cases (e.g., alternatives that share a prefix like `(ab|a)`, or patterns whose numeric backreferences depend on the textual order of capturing groups). The rule avoids such changes when it detects risk; otherwise, prefer `type: 'unsorted'` or disable the rule locally for those patterns.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
The rule is **safe**it only reorders elements without changing their meaning.
Important: Reordering can change behavior in specific cases (e.g., alternatives that share a prefix like `(ab|a)`, or patterns whose numeric backreferences depend on the textual order of capturing groups). The rule avoids such changes when it detects risk; otherwise, prefer `type: 'unsorted'` or disable the rule locally for those patterns.
🤖 Prompt for AI Agents
In docs/content/rules/sort-regexp.mdx around lines 22-23, the claim "The rule is
**safe** – it only reorders elements without changing their meaning." overstates
safety; update the text to add a short caveat and guidance: state that
reordering alternations can change behavior for patterns with shared prefixes
(e.g., (ab|a)) and when numeric capture group indices are relied upon by
backreferences, and advise when the rule is safe to apply (alternations are
independent, use non-capturing groups (?:...) or named captures to preserve
backreference semantics) and when to avoid it; include one minimal example of a
problematic case and a recommended fix or workaround (use non-capturing groups
or reorder/escape to preserve intended match) so readers know when to
enable/disable the rule.

## Try it out

<CodeExample
alphabetical={dedent`
const patterns = {
alternatives: /(apple|banana|orange|pear)/,
alias: /(?<role>administrator|guest|user)/,
characterClass: /[0-9A-Za-fz]/,
flags: /pattern/gimsuy,
}
`}
lineLength={dedent`
const patterns = {
alternatives: /(banana|orange|apple|pear)/,
alias: /(?<role>administrator|guest|user)/,
characterClass: /[0-9A-Za-fz]/,
flags: /pattern/yusmig,
}
`}
initial={dedent`
const patterns = {
alternatives: /(pear|apple|orange|banana)/,
alias: /(?<role>user|administrator|guest)/,
characterClass: /[z0-9a-fA-Z]/,
flags: /pattern/yusmig,
}
`}
client:load
lang="tsx"
/>

## Options

This rule accepts an options object with the following properties:

### type

<sub>default: `'alphabetical'`</sub>

Specifies the sorting strategy applied to matches (flags, character-class elements, and alternation branches).

- `'alphabetical'` — Sort values alphabetically using [`localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare).
- `'natural'` — Sort values in [natural](https://github.com/yobacca/natural-orderby) order (e.g., `(?=2)` comes before `(?=10)`).
- `'line-length'` — Sort values by their textual length.
- `'custom'` — Sort values according to a custom alphabet defined in [`alphabet`](#alphabet).
- `'unsorted'` — Do not reorder values. [`groups`](#groups) and [`customGroups`](#customgroups) are still applied.

### order

<sub>default: `'asc'`</sub>

Specifies the direction of sorting.

- `'asc'` — Ascending order (shorter to longer, A to Z).
- `'desc'` — Descending order (longer to shorter, Z to A).

### fallbackSort

<sub>
type:
```ts
{
type: 'alphabetical' | 'natural' | 'line-length' | 'custom' | 'unsorted'
order?: 'asc' | 'desc'
}
```
</sub>
<sub>default: `{ type: 'unsorted' }`</sub>

Used when the primary [`type`](#type) considers two values equal. For example, rely on alphabetical order when two branches share the same length.

### alphabet

<sub>default: `''`</sub>

Defines the custom alphabet for `'custom'` sorting. Use the [`Alphabet` helper](https://perfectionist.dev/alphabet) to build consistent alphabets quickly.

### locales

<sub>default: `'en-US'`</sub>

Locales passed to `localeCompare` when alphabetical comparisons are required.

### ignoreCase

<sub>default: `true`</sub>

Whether comparisons should be case-insensitive.

- `true` — Treat upper- and lowercase branches as equal (default).
- `false` — Preserve case sensitivity.

### specialCharacters

<sub>default: `'keep'`</sub>

Controls how special characters are handled before comparison.

- `'keep'` — Keep them (default).
- `'trim'` — Trim leading special characters.
- `'remove'` — Remove all special characters.

### ignoreAlias

<sub>default: `false`</sub>

Determines whether named capturing group aliases (e.g., `(?<role>...)`) are considered during comparison.

- `false` — Sort by `alias: pattern` (default).
- `true` — Ignore the alias and only compare the branch content.

This is useful when you only care about the pattern and not how it is aliased.

### customGroups

<sub>
type: `Array<CustomGroupDefinition | CustomGroupAnyOfDefinition>`
</sub>
<sub>default: `[]`</sub>

Define custom groups to control how alternatives are organized before sorting.

```ts
interface CustomGroupDefinition {
groupName: string
selector?: 'alias' | 'pattern'
elementNamePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
elementValuePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
type?: 'alphabetical' | 'natural' | 'line-length' | 'custom' | 'unsorted'
order?: 'asc' | 'desc'
fallbackSort?: { type: string; order?: 'asc' | 'desc' }
}

interface CustomGroupAnyOfDefinition {
groupName: string
anyOf: Array<{
selector?: 'alias' | 'pattern'
elementNamePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
elementValuePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
}>
type?: 'alphabetical' | 'natural' | 'line-length' | 'custom' | 'unsorted'
order?: 'asc' | 'desc'
fallbackSort?: { type: string; order?: 'asc' | 'desc' }
}
```

Attributes:

- `groupName` — Identifier referenced in [`groups`](#groups).
- `selector` — Filter by element type:
- `'alias'` — Named capturing group alternatives.
- `'pattern'` — Plain alternatives without aliases.
- `elementNamePattern` — Regex applied to the alias (if present).
- `elementValuePattern` — Regex applied to the branch content.
- `type`, `order`, `fallbackSort` — Override the respective global options for the group.

Custom groups are evaluated in order; the first match wins and overrides predefined groups.

### groups

<sub>
type: `Array<string | string[]>`
</sub>
<sub>default: `[]`</sub>

Controls the order in which groups are evaluated. Use the selectors from [`customGroups`](#customgroups) or custom group names. When an element does not match any provided group, it falls back to the implicit `unknown` group at the end of the list.

You can combine multiple groups by wrapping them in an array; all members will be sorted together using the global or overridden options.

## Usage

<CodeTabs
code={[
{
source: dedent`
// eslint.config.js
import perfectionist from 'eslint-plugin-perfectionist'

export default [
{
plugins: {
perfectionist,
},
rules: {
'perfectionist/sort-regexp': [
'error',
{
type: 'alphabetical',
order: 'asc',
fallbackSort: { type: 'unsorted' },
ignoreCase: true,
ignoreAlias: false,
specialCharacters: 'keep',
locales: 'en-US',
alphabet: '',
groups: [],
customGroups: [],
},
],
},
},
]
`,
name: 'Flat Config',
value: 'flat',
},
{
source: dedent`
// .eslintrc.js
module.exports = {
plugins: [
'perfectionist',
],
rules: {
'perfectionist/sort-regexp': [
'error',
{
type: 'alphabetical',
order: 'asc',
fallbackSort: { type: 'unsorted' },
ignoreCase: true,
ignoreAlias: false,
specialCharacters: 'keep',
locales: 'en-US',
alphabet: '',
groups: [],
customGroups: [],
},
],
},
}
`,
name: 'Legacy Config',
value: 'legacy',
},
]}
type="config-type"
client:load
lang="tsx"
/>

## Version

This rule was introduced in [v5.0.0](https://github.com/azat-io/eslint-plugin-perfectionist/releases/tag/v5.0.0).

## Resources

- [Rule source](https://github.com/azat-io/eslint-plugin-perfectionist/blob/main/rules/sort-regexp.ts)
- [Test source](https://github.com/azat-io/eslint-plugin-perfectionist/blob/main/test/rules/sort-regexp.test.ts)
1 change: 1 addition & 0 deletions docs/public/llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ Key features:
- [sort-named-imports](https://perfectionist.dev/rules/sort-named-imports): Sort named imports
- [sort-object-types](https://perfectionist.dev/rules/sort-object-types): Sort TypeScript object type properties
- [sort-objects](https://perfectionist.dev/rules/sort-objects): Sort object properties
- [sort-regexp](https://perfectionist.dev/rules/sort-regexp): Sort regular expressions
- [sort-sets](https://perfectionist.dev/rules/sort-sets): Sort Set elements
- [sort-switch-case](https://perfectionist.dev/rules/sort-switch-case): Sort switch statement cases
- [sort-union-types](https://perfectionist.dev/rules/sort-union-types): Sort TypeScript union types
Expand Down
3 changes: 3 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import sortImports from './rules/sort-imports'
import sortExports from './rules/sort-exports'
import sortObjects from './rules/sort-objects'
import sortModules from './rules/sort-modules'
import sortRegexp from './rules/sort-regexp'
import sortEnums from './rules/sort-enums'
import sortMaps from './rules/sort-maps'
import sortSets from './rules/sort-sets'
Expand All @@ -45,6 +46,7 @@ interface PluginConfig {
'sort-imports': Rule.RuleModule
'sort-exports': Rule.RuleModule
'sort-objects': Rule.RuleModule
'sort-regexp': Rule.RuleModule
'sort-enums': Rule.RuleModule
'sort-sets': Rule.RuleModule
'sort-maps': Rule.RuleModule
Expand Down Expand Up @@ -92,6 +94,7 @@ export let rules = {
'sort-imports': sortImports,
'sort-exports': sortExports,
'sort-objects': sortObjects,
'sort-regexp': sortRegexp,
'sort-enums': sortEnums,
'sort-sets': sortSets,
'sort-maps': sortMaps,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"test:unit": "vitest --run --coverage"
},
"dependencies": {
"@eslint-community/regexpp": "^4.12.1",
"@typescript-eslint/utils": "^8.45.0",
"natural-orderby": "^5.0.0"
},
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ module.exports = {
| [sort-named-imports](https://perfectionist.dev/rules/sort-named-imports) | Enforce sorted named imports | 🔧 |
| [sort-object-types](https://perfectionist.dev/rules/sort-object-types) | Enforce sorted object types | 🔧 |
| [sort-objects](https://perfectionist.dev/rules/sort-objects) | Enforce sorted objects | 🔧 |
| [sort-regexp](https://perfectionist.dev/rules/sort-regexp) | Enforce sorted regular expressions | 🔧 |
| [sort-sets](https://perfectionist.dev/rules/sort-sets) | Enforce sorted Set elements | 🔧 |
| [sort-switch-case](https://perfectionist.dev/rules/sort-switch-case) | Enforce sorted switch case statements | 🔧 |
| [sort-union-types](https://perfectionist.dev/rules/sort-union-types) | Enforce sorted union types | 🔧 |
Expand Down
Loading