Alan Mendelevich
Alan Mendelevich

Reputation: 3611

Regex with all optional parts but at least one required

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.

Upvotes: 2

Views: 3013

Answers (3)

Kilian Foth
Kilian Foth

Reputation: 14396

It is pointless to try to pack all functionality of all problems you ever have into one single regexp. The best solution is to write the obvious regex, and add a check against zero length. You should only get extra clever with regexps when you absolutely have to - for instance if you have to interact with an unchangeable API that accepts only one regexp and nothing more.

Upvotes: -2

Thexa4
Thexa4

Reputation: 99

^(?=.)a?b?c?$

This will check if there is at least one character with lookahead and will match your regex.

Upvotes: 7

Welbog
Welbog

Reputation: 60458

To do this with pure regex you're going to have to expand it into all of its possibilities:

ab?c?|a?bc?|a?b?c

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:

^(?=[abc])a?b?c?$

Or you could just test your string's length before matching it:

if (YourString.Length == 1) {
   // matching code goes here, using the expression a?b?c?
}

Upvotes: 2

Related Questions