PCRE to JavaScript RegExp Converter
pcre-to-regexp is a utility library designed to convert Perl Compatible Regular Expression (PCRE) strings into native JavaScript RegExp instances. It supports parsing PCRE patterns, including handling delimiters and flags, and can extract named capture group keys. The current stable version is 1.1.0. The project maintains a somewhat irregular release cadence, with the last major update (v1.0.0) occurring relatively recently, primarily focusing on a refactor to TypeScript for improved type safety and maintainability. Its key differentiator lies in its specialized focus on PCRE conversion, which is useful for migrating regular expressions from environments like PHP (which heavily uses PCRE) to JavaScript, although it notes it's not yet feature-complete for all PCRE constructs.
Common errors
-
TypeError: PCRE is not a function
cause Attempting to use `require('pcre-to-regexp')` and then directly calling `PCRE()`, but the CommonJS import might resolve differently in some environments, or in ESM contexts, a default import was not used.fixFor CommonJS, try `const PCRE = require('pcre-to-regexp').default;` or ensure your module resolver correctly handles default exports from ESM. For ESM, use `import PCRE from 'pcre-to-regexp';`. -
TS2305: Module '"pcre-to-regexp"' has no exported member 'PCRE'.
cause Attempting to import `PCRE` as a named export when it's primarily a default export, or trying to import a type that is within a namespace without the correct syntax.fixFor the default function, use `import PCRE from 'pcre-to-regexp';`. For types, ensure you are using `import type { PCRE } from 'pcre-to-regexp';` as of v1.1.0, specifically for type-related imports.
Warnings
- breaking Version 1.0.0 introduced a significant refactor to TypeScript, which might cause subtle type-related issues or require minor adjustments in existing TypeScript projects.
- gotcha The library is not fully feature-complete for all PCRE constructs. Complex or very specific PCRE features might not be correctly translated, leading to unexpected behavior or incorrect RegExp patterns.
- gotcha Named capture groups are not automatically added as properties to the `RegExpMatchArray` object returned by `RegExp.prototype.exec()`. A manual iteration over the `keys` array is required.
- gotcha Incorrect handling of PCRE delimiters (e.g., unmatched delimiters or delimiters appearing within the pattern without proper escaping) can lead to parsing errors or malformed JavaScript RegExp objects.
Install
-
npm install pcre-to-regexp -
yarn add pcre-to-regexp -
pnpm add pcre-to-regexp
Imports
- PCRE
const PCRE = require('pcre-to-regexp');import PCRE from 'pcre-to-regexp';
- PCRE (TypeScript type)
import { PCRE } from 'pcre-to-regexp';import type { PCRE } from 'pcre-to-regexp';
Quickstart
import PCRE from 'pcre-to-regexp';
const url = '%^https?://twitter\\.com(/\\#\\!)?/(?P<username>[a-zA-Z0-9_]{1,20})\\/status(es)?/(?P<id>\\d+)/?$%ig';
// parse the PCRE regexp into a JS RegExp
const keys = [];
const re = PCRE(url, keys);
console.log('Extracted keys:', keys);
// Expected: [ , 'username', , 'id' ]
console.log('Resulting RegExp:', re);
// Expected: /^https?:\/\/twitter\\.com(\/\\#\\!)?\/([a-zA-Z0-9_]{1,20})\\/status(es)?\/(\\d+)\/?)?$/gi
const match = re.exec('https://twitter.com/tootallnate/status/481604870626349056');
console.log('Match result:', match);
// Example of copying named captures to the match object
if (match) {
for (let i = 0; i < keys.length; i++) {
if (typeof keys[i] === 'string') {
match[keys[i]] = match[i + 1];
}
}
console.log('Username from named capture:', match.username);
console.log('ID from named capture:', match.id);
} else {
console.log('No match found.');
}