Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial matching a string against a regex

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 inputs "ab", it fails as an match for the regex, but I can't disallow entering "a" and then "b" as user can't enter all 4 characters at once (except for copy/paste). So what I need here is a partial match which checks if an incomplete string can be potentially a match for a regex.

Java has something for this purpose: .hitEnd() (described here http://glaforge.appspot.com/article/incomplete-string-regex-matching) python doesn't do it natively but has this package that does the job: https://pypi.python.org/pypi/regex.

I didn't find any solution for it in js. It's been asked years ago: Javascript RegEx partial match and even before that: Check if string is a prefix of a Javascript RegExp

P.S. regex is custom, suppose that the user enters the regex herself and then tries to enter a text that matches that regex. The solution should be a general solution that works for regexes entered at runtime.

like image 858
Sassan Avatar asked Aug 31 '25 18:08

Sassan


2 Answers

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).

like image 198
Lucas Trzesniewski Avatar answered Sep 02 '25 06:09

Lucas Trzesniewski


As many have stated there is no standard library, fortunately I have written a Javascript implementation that does exactly what you require. With some minor limitation it works for regular expressions supported by Javascript. see: incr-regex-package.

Further there is also a react component that uses this capability to provide some useful capabilities:

  1. Check input as you type
  2. Auto complete where possible
  3. Make suggestions for possible input values

Demo of the capabilities Demo of use

like image 36
NurulC Avatar answered Sep 02 '25 06:09

NurulC