Giter VIP home page Giter VIP logo

magic-regexp's Introduction

πŸ¦„ magic-regexp

npm version npm downloads Github Actions Codecov Bundlephobia

A compiled-away, type-safe, readable RegExp alternative

Features

  • Runtime is zero-dependency and ultra-minimal
  • Ships with transform to compile to pure RegExp
  • Automatically typed capture groups
  • Natural language syntax
  • Generated RegExp displays on hover

πŸ“– Β Read more

πŸ’» Development

  • Clone this repository
  • Enable Corepack using corepack enable (use npm i -g corepack for Node.js < 16.10)
  • Install dependencies using pnpm install
  • Run interactive tests using pnpm dev

Similar packages

License

Made with ❀️

Published under MIT License.

magic-regexp's People

Contributors

aykutkardas avatar barbapapazes avatar ccjmne avatar danielroe avatar didavid61202 avatar exer7um avatar kongmoumou avatar krowter avatar lgtm-com[bot] avatar moshetanzer avatar ordago avatar renovate[bot] avatar serkodev avatar xrsquared avatar yjl9903 avatar zoeyzhao19 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

magic-regexp's Issues

Incorrect open graph image

πŸ“š Is your documentation request related to a problem?

If you share the url https://regexp.dev/ it shows a completely different open graph image of Docus instead of the library.

πŸ” Where should you find it?

Just send https://regexp.dev/ on discord or twitter

ℹ️ Additional context

No response

`Predefined Input can not be assigned to InputSource` when using with TypeScript < 4.7

I just installed magic-regexp via yarn add magic-regexp and tried the first example from https://regexp.dev/getting-started/examples

Typescript does not like it though: Argument of type 'Input<"\\d", never>' is not assignable to parameter of type 'InputSource<string, never>'.

The code can also be simplified even more:
const regex = createRegExp(oneOrMore(digit));

I have created a codesandbox for showcasing this: https://codesandbox.io/s/gracious-swartz-3sdfcs

differentiate lowercase letter, uppercase letter, or combine them

πŸ†’ Your use case

right now the function letter is include all the uppercase and lowercase letter, my use case is i only need the lowercase letter, and uppercase letter is prohibited.

πŸ” Alternatives you've considered

No response

ℹ️ Additional info

No response

not.word is not defined

πŸ› The bug

In the docs it is written not can be prefixed before word, wordChar, wordBoundary, digit, whitespace, letter, letter.lowercase, letter.uppercase, tab, linefeed or carriageReturn.

But when i used it in my javascript project it returns undefined

Steps to reproduce:

  1. create new index.js
  2. run npm init -y
  3. install magic-regexp package
    4:
    import {not} from 'magic-regexp'

//const regexp = createRegExp(not.word.times); <- error

console.log(Object.keys(not).includes('word')) //false
console.log(Object.keys(not).includes('wordChar')) //true

πŸ› οΈ To reproduce

https://stackblitz.com/edit/github-cr7ofh?file=index.mjs

🌈 Expected behaviour

Expected that not.word would not be undefined as it was in the docs

ℹ️ Additional context

No response

[QUESTION] How to create typed function with RegExp or MagicRegExp input? (TypeScript)

πŸ“š Is your documentation request related to a problem?

How to create typed function with RegExp or MagicRegExp input?

I write something like

function getMatchedResult<R extends MagicRegExp<any, any, any, any> | RegExp>(regexp: R, str: string) {
	return str.match(regexp);
}

it doesn't matter Magic Regexp or just Regexp you place the function ReturnType is RegExpMatchArray | null

And is it possible not to use magic regexp as a dependency but to support it? (for example maybe implement compability types)

I am the maintainer of the Telegram Bot API framework - GramIO
And if i add support magic-regexp it would be amazing

image

I need to allow magic (with type-safety) and not regexp

πŸ” Where should you find it?

No response

ℹ️ Additional context

No response

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (:automergeEarlyMondays). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

how do i recreate a password requirements regex?

πŸ“š Is your documentation request related to a problem?

i'm trying to recreate a password requirements regex like the following:
password must contains al least 8 characters, one lowercase character, one uppercase char, one digit and one special character (! @ # $ % ^ & *)

const PASSWORD_RE= createRegExp(
  (
    oneOrMore(letter.lowercase).times.atLeast(1)
  .and(oneOrMore(letter.uppercase).times.atLeast(1))
  .and(oneOrMore(digit))
  .and(
    oneOrMore(
      charIn('!')
      .or(charIn('@'))
      .or(charIn('#'))
      .or(charIn('$'))
      .or(charIn('%'))
      .or(charIn('^'))
      .or(charIn('&'))
      .or(charIn('*'))
      ).times.atLeast(1)
    )
  )
.times.atLeast(8),['g']
)

i tried to paste the generated regex in one of the regex tester like regex101
but seems to not working as expected

the documentation seems lacking in terms of providing a fully understandable examples

can you help me to achieve a working password regex? Where am I doing wrong?

πŸ” Where should you find it?

No response

ℹ️ Additional context

No response

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update devdependency undocs to v0.2.21
  • chore(deps): update devdependency vite to v5.2.10
  • chore(deps): update devdependency @antfu/eslint-config to v2.16.1
  • chore(deps): update devdependency @nuxt/kit to v3.11.2
  • chore(deps): update devdependency @types/node to v20.12.7
  • chore(deps): update devdependency expect-type to v0.19.0
  • chore(deps): update devdependency rollup to v4.17.2
  • chore(deps): update devdependency simple-git-hooks to v2.11.1
  • chore(deps): update test packages to v1.5.3 (@vitest/coverage-v8, vitest)

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update devdependency bumpp to v9.4.1
  • chore(deps): update pnpm to v8.15.8
  • chore(deps): update devdependency eslint to v9
  • chore(deps): update pnpm to v9
  • chore(deps): lock file maintenance
  • πŸ” Create all rate-limited PRs at once πŸ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/bench.yml
  • actions/checkout v4
  • pnpm/action-setup v2
  • actions/setup-node v4
  • CodSpeedHQ/action v2
.github/workflows/ci.yml
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4
  • codecov/codecov-action v4
.github/workflows/codeql.yml
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/performance.yml
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4
  • beerose/tsc-diagnostics-diff-action 49bf67cb35cae2ba688d1e7dffe5f14acbb62406
.github/workflows/release.yml
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4
npm
docs/package.json
  • undocs 0.2.20
package.json
  • estree-walker ^3.0.3
  • magic-string ^0.30.8
  • mlly ^1.6.1
  • regexp-tree ^0.1.27
  • type-level-regexp ~0.1.17
  • ufo ^1.4.0
  • unplugin ^1.8.3
  • @antfu/eslint-config 2.8.0
  • @codspeed/vitest-plugin 3.1.0
  • @nuxt/kit 3.10.3
  • @types/estree 1.0.5
  • @types/node 20.11.30
  • @vitest/coverage-v8 1.3.1
  • acorn 8.11.3
  • bumpp 9.4.0
  • eslint 8.57.0
  • expect-type 0.18.0
  • rollup 4.12.1
  • simple-git-hooks 2.10.0
  • typescript 5.4.5
  • unbuild 2.0.0
  • vite 5.2.8
  • vitest 1.3.1
  • pnpm 8.15.7
playground/package.json

  • Check this box to trigger a request for Renovate to run again on this repository

Does the look behind operator work with safari?

I saw this example on the documentation.

import { createRegExp, exactly } from 'magic-regexp'

const regExp = createRegExp(exactly('foo/test.js').after('bar/'))
console.log(regExp)

// /(?<=bar\/)foo\/test\.js/

This example can work with safari?

Maige Usage

Thanks for trying Maige.

Running GPT-based services is pricey. At this point, we ask you to add payment info to continue using Maige.

Add payment info

Feel free to close this issue.

Support match everything in preset inputs

πŸ†’ Your use case

I want to match all characters within a script tag, but since there isn't a preset input to match everything, so I have to manually write ([\s\S]*?) for match the code.

πŸ” Alternatives you've considered

Maybe an export named every can be added to preset inputs, or export createInput to allow for custom input definitions could be a solution ?

ℹ️ Additional info

No response

performance testing

with the amount of inference we're doing, it would be a great enhancement to add some kind of type performance test to ensure that end users' TS checkers or IDEs don't get slower. With metrics, we also will have a basis for making performance improvements.

Why is `MagicRegExpMatchArray` typed with `string | undefined`?

Hi

First, thank you so much for this library. I love it so far. I came across a typing issue while trying it out, and thought I'd report it.

πŸ› The bug

const regex = createRegExp(
  anyOf('A', 'B', 'C')
    .groupedAs('opponent')
    .and(' ')
    .and(anyOf('X', 'Y', 'Z').groupedAs('self'))
);

// Results in: /(?<opponent>A|B|C) (?<self>X|Y|Z)/

console.log('A Y'.match(regex)?.groups); // { opponent: 'A', self: 'Y' }
console.log('B '.match(regex)?.groups); // undefined
console.log('C Z'.match(regex)?.groups); // { opponent: 'C', self: 'Z' }

The type of each groups is Record<"opponent" | "self", string | undefined>.

Why is the type in
https://github.com/danielroe/magic-regexp/blob/50ac0caa55e6e3fe2c7397297d8a1533190c5012/src/core/types/magic-regexp.ts#L35

defined as string | undefined?

How can the value of the group be undefined while still matching the reg exp?

πŸ› οΈ To reproduce

https://stackblitz.com/edit/github-ppjiny?file=index.ts

🌈 Expected behaviour

The type of each groups should be Record<"opponent" | "self", string>.

ℹ️ Additional context

No response

feat: Turn existing regex to this

πŸ†’ Your use case

There are lot of regex being used in codebase. And if there is an easy way to put them in playground and get the equivalent of it in magic-regex - it will be awesome

πŸ†• The solution you'd like

There are lot of regex being used in codebase. And if there is an easy way to put them in playground and get the equivalent of it in magic-regex - it will be awesome

πŸ” Alternatives you've considered

No response

ℹ️ Additional info

No response

improvements to anonymous groups

  • #28
  • Type inference of number of anonymous groups? E.g. type safe array access? (possibly default to non-capturing groups, requiring opt-in?)
  • Better way to expose what each anonymous groups refers to for ease of use...?

Allow for custom regex, and clarifying the usage of `anyOf()`

@didavid61202 @danielroe , As I was working on issue #7, two issues/points of clarification for the API came to mind.

Allowing for custom regex patterns

Unless there is a function that I don't know of, a user can't add to an expression using custom regex unless it is exported as one of the helpers for specific RegExp characters such as digit, whitespace, letter, etc. For example, using the current API there is no way to include the following regex pattern [1-9] without it being passed to exactly() and ending up as \[1-9\].

import { exactly } from "magic-regexp";

const test = exactly("foo").and("[1-9]"); // foo\[1-9\]

Note: the regex pattern was passed to exactly() here

When working within the package, we can create these arbitrary regex patterns using createInput(); however, this function isn't exported to end users.

Possible Solutions

  1. export an alias for createInput named one of the following input, rawInput,regex, or some other suggestion
  2. leave as is and don't allow users to use custom regex patterns (I don't think this is an end goal of the package)

Providing an alias to createInput would allow for patterns such as:

import { exactly, input } from "magic-regexp";

const test = exactly("foo").and(input("[1-9]")); // foo[1-9]

anyOf

@didavid61202 @danielroe, the anyOf function states that it takes an array of inputs, but it doesn't really take an array; it takes an arbitrary number of arguments. The function documentation stating it takes an array can lead to confusion, and in fact, it confused me when I first started using this package.

Consider the following examples:

import { anyOf } from "magic-regexp";

const test1 = anyOf(...["a", "b", "c"]); //(?:a|b|c)
const test2 = anyOf("a", "b", "c"); //(?:a|b|c)
const test3 = anyOf(["a", "b", "c"]); //(?:a,b,c)
const test4 = anyOf("abc"); //(?:abc)

Possible Solutions

  1. leave as is, and change the documentation
  2. accept arrays, and do the array unpacking within the function
  3. overload the function to allow for the passing of arrays

Documentation site is down

πŸ› The bug

Visiting https://regexp.dev/ returns a 500: INTERNAL_SERVER_ERROR, preventing anyone from accessing the really important documentation.

πŸ› οΈ To reproduce

https://regexp.dev/

🌈 Expected behaviour

The website should load.

ℹ️ Additional context

No response

fix: fail importing estree-walker with unbuild

πŸ› The bug

Error trying import ./build.config from /workspaces/Optc Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /workspaces/Optc/node_modules/.pnpm/[email protected][email protected]/node_modules/estree-walker/package.json
    at new NodeError (node:internal/errors:371:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:453:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:671:7)
    at resolveExports (node:internal/modules/cjs/loader:482:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.resolve (node:internal/modules/cjs/helpers:108:19)
    at _resolve (/workspaces/Optc/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/jiti.js:1:108226)
    at jiti (/workspaces/Optc/node_modules/.pnpm/[email protected]/node_modules/jiti/dist/jiti.js:1:110413)
    at /workspaces/Optc/node_modules/.pnpm/[email protected][email protected]/node_modules/magic-regexp/dist/transform.mjs:3:21 {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

πŸ› οΈ To reproduce

https://stackblitz.com/edit/github-dpu8mc?file=build.config.ts

🌈 Expected behaviour

It should build.

ℹ️ Additional context

An issue about estree-walker: Rich-Harris/estree-walker#26

feat: Documentation

πŸ†’ Your use case

creating project documentation, documentation even at the beginning of the project is important for more people to test and give more ideas and get feedback from the community.

πŸ†• The solution you'd like

Vitepress, is powerful and can be easily implemented.

πŸ” Alternatives you've considered

No response

ℹ️ Additional info

No response

No "exports" main defined in ....\.pnpm\[email protected]\node_modules\estree-walker\package.json

πŸ› The bug

After running pnpm install and adding to vite.config.ts, I got the following error. I'm using vite 4 and pnpm

failed to load config from C:\Git\BlocPlatform\Bloc\Frontend\Bloc.Vue\vite.config.ts
error when starting dev server:
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:\Git\BlocPlatform\Bloc\Frontend\Bloc.Vue\node_modules\.pnpm\[email protected]\node_modules\estree-walker\package.json
    at new NodeError (node:internal/errors:372:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:472:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:693:7)
    at resolveExports (node:internal/modules/cjs/loader:482:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\Git\BlocPlatform\Bloc\Frontend\Bloc.Vue\node_modules\.pnpm\[email protected]\node_modules\magic-regexp\dist\transform.cjs:5:22)

 *  The terminal process "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -Command npm run dev" terminated with exit code: 1. 
 *  Terminal will be reused by tasks, press any key to close it. 

πŸ› οΈ To reproduce

n/a

🌈 Expected behaviour

Expected config to load.

ℹ️ Additional context

No response

Infer the literals used in the type of the groups

πŸ†’ Your use case

When I create a regexp group using anyOf and groupedAs, the type of the matched group should be inferred based on the inputs to anyOf.

Similar to the type of the main regexp that gets inferred.

E.g.

const regex = createRegExp(
  anyOf("A", "B", "C")
    .groupedAs("opponent")
    .and(" ")
    .and(anyOf("X", "Y", "Z").groupedAs("self")),
);

Here, the type of regex is

MagicRegExp<"/(?<opponent>A|B|C) (?<self>X|Y|Z)/", "opponent" | "self", ["(?<opponent>A|B|C)", ...any[]], never>

so the information that the groups have literals of ABC and XYZ respectively is included in the type. However, the type of

"A Y".match(regex)?.groups.opponent

is string | undefined instead of "A" | "B" | "C".

πŸ” Alternatives you've considered

No response

ℹ️ Additional info

My goal is to use this library in conjunction with colinhacks/zod. magic-regexp complements zod well when it comes to string validation and parsing while still being typesafe.

I'm open to work on this myself. Please let me know where I should have a look to get started with such a feature.

Library blocks Typescript compilation

πŸ› The bug

When Trying to build a Typescript Project using magic-regexp tsc hangs indefinitely.
It just hangs and does nothing.

The Problem occurred in different projects (finding the problem the first time did cost me a good amount of time).

πŸ› οΈ To reproduce

https://stackblitz.com/edit/github-dmq6xe?file=package.json

🌈 Expected behaviour

The build Process should go through or at least throw an error.

ℹ️ Additional context

When using ts-node to run the Script it works for whatever reason.

I've added a build script & a start:ts-node script to the example.

Lazy quantifier

πŸ“š Is your documentation request related to a problem?

Is it possible to use this library and create the lazy quantifier?
For example I would like to get such regex: (?:\w|-)+?. The main part I'm asking here is the +?.

πŸ” Where should you find it?

No response

ℹ️ Additional context

No response

fix: can't import transform in vite project without `type: module`

πŸ› The bug

When I try to use magic-regexp in a Laravel + Vite project I get the following errors:

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/hassan/project/node_modules/.pnpm/[email protected][email protected]/node_modules/magic-regexp/dist/transform.mjs not supported.

πŸ› οΈ To reproduce

You can easily reproduce by following these steps:

laraven new
npx @preset/cli apply laravel:inertia
php artisan serve
npm run dev

When you add the vite plugin, you will see the dev command will fail with error.

🌈 Expected behaviour

I expect it to work based on the project readme instructions and code examples.

ℹ️ Additional context

No response

Can I rework docs using Nuxt UI Pro

πŸ†’ Your use case

Hello,

Current docs is built with docus which is currently deprecated. Nitro and H3 will use Nuxt UI Pro in a near future. Can I do the same for the current lib?

πŸ” Alternatives you've considered

No response

ℹ️ Additional info

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.