Check if string is a prefix of a Javascript RegExp

后端 未结 5 2132
旧巷少年郎
旧巷少年郎 2021-01-04 03:31

In Javascript I have defined a regular expression and now a user is typing in a string. I want to tell him if his string still could match the RegExp if he continues typing

5条回答
  •  悲&欢浪女
    2021-01-04 04:12

    I think your best bet here is to make your Regex prefix-proof. For the example you gave, /a*b/, I think you could probably use /a*b?/.test(userinput). For more complex patterns this could get increasingly difficult, but I still think it can be done by nesting each subexpression in a series of optional quantifiers (?). For instance:

    /a*bcd*e/
    

    The prefix regex could be:

    /a*(b(c(d*e?)?)?)?/
    

    Its a little messy, but will solve your problem rather well I think.

提交回复
热议问题