-
Notifications
You must be signed in to change notification settings - Fork 54
feat: add sort-regexp rule #600
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
azat-io
wants to merge
1
commit into
next
Choose a base branch
from
feat/sort-regexp
base: next
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,873
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
||
## 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.📝 Committable suggestion
🤖 Prompt for AI Agents