Matt
Matt

Reputation: 26981

RegEx valid until it is not

Let's say I want to match the following javascript

\d{1,3}[a-zA-Z]{1,3}\d{1,3}[a-zA-Z]{1,3}

as I'm entering things like

1asd23a

311eed123ss

So far so good; but I would rather not say valid or invalid after the whole string has been entered but rather as the string is being entered, I would like to return whether it could still potentially be valid.

Basically StartsWith but with any segment of the regex.

1asd23

311eed12

would still be valid because the entry could still be amended into the final form. The beginning characters are not the ones that will make the regex invalid.

I hope I'm explaining this correctly.

Upvotes: 1

Views: 39

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208575

Makes the regex quite a bit uglier, but one option would be to make all of the later elements optional. This needs to be done carefully to ensure that the later elements can only exist if all of the earlier ones do, so you will end up nesting several optional groups. For example:

\d{1,3}([a-zA-Z]{1,3}(\d{1,3}([a-zA-Z]{1,3})?)?)?

Of course when the final string is entered you will want to validate it against your original regex.

Upvotes: 1

Related Questions