Basically, if I've a RegEx like
/^(foo|bars)$/
I'd like it to be successful for
['', 'f', 'fo', 'foo', 'b', 'ba', 'bar', 'bars']
but then fail for the likes of
['j', 'fa', 'foos'...]
I was aware of some of the answers that have been given,
/^(f(oo?)?|b(ar?)?)$/
or
/^f|fo|foo|b|ba|bar$/
and while they do work, for this specific case, that's not the way I'd rather go, if this were expanded to 20 long words, it becomes unmanageable. I'd love a more elegant solution if it's possible.
Any elegant ideas? Where I'm using it, I can, rather than a RegEx, pass a list of Strings, then just check if the index of the input is 0 for any of the Strings, but I just wanted to see if there's a way you can do it with a Regular Expression.
Thanks for all the answers, but I'm mostly looking for a as-much-as-possible 'elegant' solution, but after looking through, I'm not sure if there is one.
Basically, it's a forced input prevention. What I wanted was similar to Dojo's ValidationTextBox, http://dojotoolkit.org/reference-guide/1.7/dijit/form/ValidationTextBox.html. There, it tells you as soon as possible if the input doesn't have a match to the validation pattern (which I... might end up doing), but I'd like to only allow correct input, and the path to it.
To rephrase, I was trying to find out if there was any elegant way to see if you could check the input string only against a pattern of it's same length, as in, if you only typed one character, it'd really only test against
/^(f|b)$/
in this case, two characters,
/^(fo|ba)$/
and so on.
While my specific answer is about alternation with regular expression, I'd love to know this about regular expression in general (from what I've read, it doesn't seem possible though).
I mean, if you had,
/^The dog$/
I'd like a way for a test to be successful for all of
['', 'T', 'Th',...'The dog']
/f|fo|foo|b|ba|bar/
Oops! Your answer couldn't be submitted because:
body must be at least 30 characters; you entered 19