Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/sindresorhus/eslint-plugin-unicorn/llms.txt

Use this file to discover all available pages before exploring further.

Regex literals often contain verbose patterns that can be expressed more concisely using shorthand character classes. This rule uses regexp-tree and clean-regexp to detect and rewrite those patterns automatically, keeping your regexes shorter and easier to read.
Recommended
Fixable🔧 Auto-fix
Suggestions
Regexes with the u or v flag are skipped because regexp-tree does not fully support them.

Examples

const regex = /[0-9]/;
const regex2 = /[^0-9]/;
const regex3 = /[a-zA-Z0-9_]/;
const regex4 = /[a-z0-9_]/i;
const regex5 = /[^a-zA-Z0-9_]/;
A combined example showing multiple optimizations in one pattern:
const regex = /[0-9]\.[a-zA-Z0-9_]\-[^0-9]/i;

Configuration

eslint.config.js
export default [
  {
    rules: {
      'unicorn/better-regex': ['error', { sortCharacterClasses: true }],
    },
  },
];

sortCharacterClasses

Type: boolean — Default: true When true, character classes are reordered for consistency (for example, [AaQqTt] becomes [AQTaqt]). Set to false to preserve the original order of characters inside character classes.
eslint.config.js
'unicorn/better-regex': ['error', { sortCharacterClasses: false }]

Build docs developers (and LLMs) love