Skip to content

buildConventionalCommitRegex

Builds a regular expression matching the subject line of a Conventional Commits message.

The returned regex exposes four capture groups:

  1. type
  2. scope (or undefined when absent)
  3. breaking marker ('!' or undefined)
  4. description

Available since v2.0.0

import { buildConventionalCommitRegex } from '@helpers4/commit';
buildConventionalCommitRegex(options: ConventionalCommitOptions): RegExp
ParameterTypeDescription
optionsConventionalCommitOptionsConstrain accepted types/scopes and toggle scope requirement.

RegExp — Regex anchored on ^...$ matching the subject line only.

Match the default Conventional Commits format

Section titled “Match the default Conventional Commits format”

Returns a regex matching type(scope)?!?: description on the subject line.

const regex = buildConventionalCommitRegex();
regex.test('feat(api): add endpoint') // => true
regex.test('not a commit') // => false

Restrict accepted types and require a scope

Section titled “Restrict accepted types and require a scope”

Constrain accepted types and force the scope segment to be present.

const regex = buildConventionalCommitRegex({
  types: ['feat', 'fix'],
  requireScope: true,
});
regex.test('feat(api): x') // => true
regex.test('feat: missing scope') // => false
regex.test('chore(api): wrong type') // => false

Options shared by buildConventionalCommitRegex, parseConventionalCommit, and isConventionalCommit to constrain the accepted commit format.

interface ConventionalCommitOptions {
  requireScope?: boolean;
  scopes?: readonly string[];
  types?: readonly string[];
}

View source on GitHub