magic-regexp icon indicating copy to clipboard operation
magic-regexp copied to clipboard

Unexpected `maybe()` result

Open Taib-Rabah opened this issue 9 months ago • 1 comments

🐛 The bug

The maybe() helper sometimes return wrong value.

For example:

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

const regexp = createRegExp(maybe(exactly('a').or('b'), exactly('1').or('2')));

// Expected: maybe (a or b then 1 or 2) // (?:(?:a|b)(?:1|2))?
// Result: a or b then maybe (1 or 2) // (?:a|b)(?:1|2)?

const tests = ['a2', 'b1', 'foo', ''];

console.table(tests.map((test) => ({ test, result: regexp.test(test) })));

// Expected: all tests should succeed // Reason: everything is wrapped in `maybe()` so it should match anything
// Result: "foo" and "" did not succeed // Reason: They do not start with (a or b)

🛠️ To reproduce

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

🌈 Expected behaviour

regexp.test(...) should succeed on any string. Reason: everything is wrapped in maybe()

ℹ️ Additional context

No response

Taib-Rabah avatar Mar 03 '25 15:03 Taib-Rabah