Partial matching a string against a regex

前端 未结 6 1748
梦毁少年i
梦毁少年i 2021-02-04 01:02

Suppose that I have this regular expression: /abcd/ Suppose that I wanna check the user input against that regex and disallow entering invalid characters in the input. When user

6条回答
  •  有刺的猬
    2021-02-04 01:36

    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 RegExp object in JS.
    • Replace abc with (?: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).

提交回复
热议问题