All Projects → lukeed → Regexparam

lukeed / Regexparam

Licence: mit
A tiny (308B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍♂️

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Regexparam

js-diacritic-regex
Creates the inverse of transliterated string to a regex. What? Basically, diacritic insensitiveness
Stars: ✭ 20 (-94.87%)
Mutual labels:  regex, regexp
RegExp-Learning
学习正则表达式
Stars: ✭ 30 (-92.31%)
Mutual labels:  regex, regexp
globrex
Glob to regular expression with support for extended globs.
Stars: ✭ 52 (-86.67%)
Mutual labels:  regex, regexp
is-regex
Is this value a JS regex?
Stars: ✭ 22 (-94.36%)
Mutual labels:  regex, regexp
mention-hashtag
Extract mentions (@mention) or hashtags (#hashtag) from any text
Stars: ✭ 16 (-95.9%)
Mutual labels:  regex, regexp
python-hyperscan
A CPython extension for the Hyperscan regular expression matching library.
Stars: ✭ 112 (-71.28%)
Mutual labels:  regex, regexp
RgxGen
Regex: generate matching and non matching strings based on regex pattern.
Stars: ✭ 45 (-88.46%)
Mutual labels:  regex, regexp
cregex
A small implementation of regular expression matching engine in C
Stars: ✭ 72 (-81.54%)
Mutual labels:  regex, regexp
String.prototype.matchAll
Spec-compliant polyfill for String.prototype.matchAll, in ES2020
Stars: ✭ 14 (-96.41%)
Mutual labels:  regex, regexp
retrie
Efficient Trie-based regex unions for blacklist/whitelist filtering and one-pass mapping-based string replacing
Stars: ✭ 35 (-91.03%)
Mutual labels:  regex, regexp
regXwild
⏱ Superfast ^Advanced wildcards++? | Unique algorithms that was implemented on native unmanaged C++ but easily accessible in .NET via Conari (with caching of 0x29 opcodes +optimizations) etc.
Stars: ✭ 20 (-94.87%)
Mutual labels:  regex, regexp
Rex
Your RegEx companion.
Stars: ✭ 283 (-27.44%)
Mutual labels:  regex, regexp
IronRure
.NET Bindings to the Rust Regex Crate
Stars: ✭ 16 (-95.9%)
Mutual labels:  regex, regexp
expand-brackets
Expand POSIX bracket expressions (character classes) in glob patterns.
Stars: ✭ 26 (-93.33%)
Mutual labels:  regex, regexp
regexp-expand
Show the ELisp regular expression at point in rx form.
Stars: ✭ 18 (-95.38%)
Mutual labels:  regex, regexp
librxvm
non-backtracking NFA-based regular expression library, for C and Python
Stars: ✭ 57 (-85.38%)
Mutual labels:  regex, regexp
regexp-example
正则表达式实例搜集,通过实例来学习正则表达式。
Stars: ✭ 162 (-58.46%)
Mutual labels:  regex, regexp
url-regex-safe
Regular expression matching for URL's. Maintained, safe, and browser-friendly version of url-regex. Resolves CVE-2020-7661 for Node.js servers.
Stars: ✭ 59 (-84.87%)
Mutual labels:  regex, regexp
stringx
Drop-in replacements for base R string functions powered by stringi
Stars: ✭ 14 (-96.41%)
Mutual labels:  regex, regexp
subst
Search and des... argh... replace in many files at once. Use regexp and power of Python to replace what you want.
Stars: ✭ 20 (-94.87%)
Mutual labels:  regex, regexp

regexparam Build Status

A tiny (308B) utility that converts route patterns into RegExp. Limited alternative to path-to-regexp 🙇

With regexparam, you may turn a pathing string (eg, /users/:id) into a regular expression.

An object with shape of { keys, pattern } is returned, where pattern is the RegExp and keys is an array of your parameter name(s) in the order that they appeared.

Unlike path-to-regexp, this module does not create a keys dictionary, nor mutate an existing variable. Also, this only ships a parser, which only accept strings. Similarly, and most importantly, regexparam only handles basic pathing operators:

  • Static (/foo, /foo/bar)
  • Parameter (/:title, /books/:title, /books/:genre/:title)
  • Parameter w/ Suffix (/movies/:title.mp4, /movies/:title.(mp4|mov))
  • Optional Parameters (/:title?, /books/:title?, /books/:genre/:title?)
  • Wildcards (*, /books/*, /books/:genre/*)

This module exposes two module definitions:

  • CommonJS: dist/regexparam.js
  • ESModule: dist/regexparam.mjs

Install

$ npm install --save regexparam

Usage

const regexparam = require('regexparam');

// Example param-assignment
function exec(path, result) {
  let i=0, out={};
  let matches = result.pattern.exec(path);
  while (i < result.keys.length) {
    out[ result.keys[i] ] = matches[++i] || null;
  }
  return out;
}


// Parameter, with Optional Parameter
// ---
let foo = regexparam('/books/:genre/:title?')
// foo.pattern => /^\/books\/([^\/]+?)(?:\/([^\/]+?))?\/?$/i
// foo.keys => ['genre', 'title']

foo.pattern.test('/books/horror'); //=> true
foo.pattern.test('/books/horror/goosebumps'); //=> true

exec('/books/horror', foo);
//=> { genre: 'horror', title: null }

exec('/books/horror/goosebumps', foo);
//=> { genre: 'horror', title: 'goosebumps' }


// Parameter, with suffix
// ---
let bar = regexparam('/movies/:title.(mp4|mov)');
// bar.pattern => /^\/movies\/([^\/]+?)\.(mp4|mov)\/?$/i
// bar.keys => ['title']

bar.pattern.test('/movies/narnia'); //=> false
bar.pattern.test('/movies/narnia.mp3'); //=> false
bar.pattern.test('/movies/narnia.mp4'); //=> true

exec('/movies/narnia.mp4', bar);
//=> { title: 'narnia' }


// Wildcard
// ---
let baz = regexparam('users/*');
// baz.pattern => /^\/users\/(.*)\/?$/i
// baz.keys => ['wild']

baz.pattern.test('/users'); //=> false
baz.pattern.test('/users/lukeed'); //=> true

exec('/users/lukeed/repos/new', baz);
//=> { wild: 'lukeed/repos/new' }

Important: When matching/testing against a generated RegExp, your path must begin with a leading slash ("/")!

Regular Expressions

For fine-tuned control, you may pass a RegExp value directly to regexparam as its only parameter.

In these situations, regexparam does not parse nor manipulate your pattern in any way! Because of this, regexparam has no "insight" on your route, and instead trusts your input fully. In code, this means that the return value's keys is always equal to false and the pattern is identical to your input value.

This also means that you must manage and parse your own keys~!
You may use named capture groups or traverse the matched segments manually the "old-fashioned" way:

Important: Please check your target browsers' and target Node.js runtimes' support!

// Named capture group
const named = regexparam(/^\/posts[/](?<year>[0-9]{4})[/](?<month>[0-9]{2})[/](?<title>[^\/]+)/i);
const { groups } = named.pattern.exec('/posts/2019/05/hello-world');
console.log(groups);
//=> { year: '2019', month: '05', title: 'hello-world' }

// Widely supported / "Old-fashioned"
const named = regexparam(/^\/posts[/]([0-9]{4})[/]([0-9]{2})[/]([^\/]+)/i);
const [url, year, month, title] = named.pattern.exec('/posts/2019/05/hello-world');
console.log(year, month, title);
//=> 2019 05 hello-world

API

There are two API variants:

  1. When passing a String input, the loose parameter is able to affect the output. View API

  2. When passing a RegExp value, that must be regexparam's only argument.
    Your pattern is saved as written, so loose is ignored entirely. View API

regexparam(str, loose)

Returns: Object

Returns a { keys, pattern } object, where pattern is a generated RegExp instance and keys is a list of extracted parameter names.

str

Type: String

The route/pathing string to convert.

Note: It does not matter if your str begins with a / — it will be added if missing.

loose

Type: Boolean
Default: false

Should the RegExp match URLs that are longer than the str pattern itself?
By default, the generated RegExp will test that the URL begins and ends with the pattern.

const rgx = require('regexparam');

rgx('/users').pattern.test('/users/lukeed'); //=> false
rgx('/users', true).pattern.test('/users/lukeed'); //=> true

rgx('/users/:name').pattern.test('/users/lukeed/repos'); //=> false
rgx('/users/:name', true).pattern.test('/users/lukeed/repos'); //=> true

regexparam(rgx)

Returns: Object

Returns a { keys, pattern } object, where pattern is identical to your rgx and keys is false, always.

rgx

Type: RegExp

Your RegExp pattern.

Important: This pattern is used as is! No parsing or interpreting is done on your behalf.

Related

  • trouter - A server-side HTTP router that extends from this module.
  • matchit - Similar (650B) library, but relies on String comparison instead of RegExps.

License

MIT © Luke Edwards

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].