I need to write a regex that matches strings like “abc”, “ab”, “ac”, “bc”, “a”, “b”, “c”. Order is important and it shouldn’t match multiple appearances of the same part.
a?b?c? almost does the trick. Except it matches empty strings too. Is there any way to prevent it from matching empty strings or maybe a different way to write a regex for the task.
To do this with pure regex you’re going to have to expand it into all of its possibilities:
If you have lookaheads you can make sure the string is non-empty. Or you can verify the string has a length of at least one before passing it to the expression, depending on your choice of language.
For example a .NET lookahead might look like this:
Or you could just test your string’s length before matching it: