Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

compose-regexp

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

compose-regexp

A set of functions to build and compose complex regular expressions

  • 0.3.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
898
decreased by-14.07%
Maintainers
1
Weekly downloads
 
Created
Source

compose-regexp.js

Build and compose maintainable regular expressions in JavaScript.

Regular expressions don't do justice to regular grammars.

  • The regular grammar/language formalism is all about expression composition.
  • Yet RegExps were designed as a write-only syntax for command line tools like ed and grep.
  • Building large expressions from smaller, abstracted patterns is not possible using RegExp literals.

This makes complex RegExps hard to read, debug and modify...

compose-regexp to the rescue!

It doesn't make regular grammars more powerful, they are still fundamentally limited, but since they are ubiquitous, we may as well have better tooling to implement them...

Usage

$ npm install --save compose-regexp
import {
    sequence, either, capture,
    ref, greedy, flags, avoid
} from "compose-regexp"; // can be required too

// the example that made me write this, in order to ~lex JS.
// It matches braces in source code, but skips comments and strings.
let matcher = flags('gm',
    either(
        sequence(
            capture(/['"`]/),
            greedy('*', // a greedy zero-or-more repetition
                either(
                    sequence('\\', ref(1)),
                    '\\\\',
                    sequence(avoid(ref(1)), /[\s\S]/)
                )
            ),
            ref(1)
        ),
        sequence(
            '/*',
            greedy('*',
                avoid('*/'),
                /[\s\S]/
            ),
            '*/'
        ),
        sequence('//', /[^\n]*\n/),
        capture(either(/[{}]/, '}}'))
    )
);

// matcher:

/(?:(['"`])(?:(?:\\\1|\\\\|(?!\1)[\s\S]))*\1|\/\*(?:(?!\*\/)[\s\S])*\*\/|\/\/[^\n]*\n|((?:[{}]|\}\})))/gm

// The most astute among you may have noticed that regexes in the subject string
// would still trip that parser. Not perfect, but still useful.

API

General (important) notes:

The regexp parameters of these functions can be either RegExps or strings. Special characters in strings are escaped, so that '.*' is equivalent to /\.\*/. Therefore:

> sequence('.', '*').source
'\\.\\*'

The flags of intermediate regexps are ignored, and always reset to false unless set by flags().

flags(opts, regexps...)
> flags('gm', /a/)
/a/gm
either(regexps...)
> either(/a/, /b/, /c/)
/(?:a|b|c)/
sequence(regexps...)
> sequence(/a/, /b/, /c/)
/abc/
lookAhead(regexps...)
> lookAhead(/a/, /b/, /c/)
/(?=abc)/
avoid(regexps...)

Negative look ahead

> avoid(/a/, /b/, /c/)
/(?!abc)/
greedy(suffix, regexprs...), greedy(suffix)(regexprs...)

Valid suffixes: (?, *, +, {n}, {n,} and {m, n})

> greedy("*", either(/a/, /b/, /c/))
/(?:a|b|c)*/
> maybe = greedy('?'); maybe(either('a', 'b'))
/(?:a|b)?/
frugal(suffix, regexprs...), frugal(suffix)(regexprs...)

Like greedy() but for non-greedy operators (??, *?, +?, {n}?, {n,}? and {m, n}?).

> frugal("{1,3}", either(/a/, /b/, /c/))
/(?:a|b|c){1,3}?/
capture (regexprs...)
> capture(/a/, /b/, /c/)
/(abc)/
ref(n)
> ref(1)
/\1/

Caveat emptor, references are absolute. Therefore, refs may be broken if you compose two regexps that use captures.


stringMatcher = sequence(
    capture(/['"`]/),
    greedy('*', // a greedy zero-or-more repetition
        either(
            sequence('\\', ref(1)),
            '\\\\',
            sequence(avoid(ref(1)), /[\s\S]/)
        )
    ),
    ref(1)
)

whooops = sequence(
    capture('foo'),
    stringMatcher
)

In whoops, the ref(1) in stringMatcher actually refers to foo, not the opening quote.

Fixing this would require an approach far more complex than what I'm doing now (concat the regexps source).

License MIT

The MIT License (MIT)

Copyright (c) 2016 Pierre-Yves Gérardy

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 30 Mar 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc