Looks like you’re lucky, I’ve already implemented that stuff in JS (which works for most patterns – maybe that’ll be enough for you). See my answer here. You’ll also find a working demo there.
There’s no need to duplicate the full code here, I’ll just state the overall process:
- Parse the input regex, and perform some replacements. There’s no need for error handling as you can’t have an invalid pattern in a
RegExpobject in JS. - Replace
abcwith(?:a|$)(?:b|$)(?:c|$) - Do the same for any “atoms”. For instance, a character group
[a-c]would become(?:[a-c]|$) - Keep anchors as-is
- Keep negative lookaheads as-is
Had JavaScript have more advanced regex features, this transformation may not have been possible. But with its limited feature set, it can handle most input regexes. It will yield incorrect results on regex with backreferences though if your input string ends in the middle of a backreference match (like matching ^(\w+)\s+\1$ against hello hel).