PCRE to JavaScript RegExp Converter

1.1.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This example demonstrates how to convert a PCRE string to a JavaScript RegExp, extract named capture group keys, and then use the resulting RegExp to match a string, showcasing access to named captures.

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.');
}

view raw JSON →