Search code examples
regexlocalizable.strings

Regex to Match sorted words and at least one


I would like to know if there is a simpler way of matching for a sequence of words were at least one is mandatory.

In order to simplify things imagine that my words are A, B and C. I want to have a match for A, B, C, AB, BC, AC but for CA it would be C and A as separated matches, the order is important. Hence the first idea I came up with:

A?B?C?

The only problem I found is that it matches also empty string and I got invalid matches. What I want is some simpler way of doing:

(AB?C?|A?BC?|A?B?C)

That matches in ABCASDBC: ABC, A, BC. My real problem can have more words and that expression can grow and have an expensive calculation cost. That's my biggest concern (a different solution without using regular expressions is welcome as well)


Solution

  • (?=[xyz])x?y?z?
    

    Or if x, y, z are not characters:

    (?=x|y|z)(?:x)?(?:y)?(?:z)?
    

    The idea is to match the existence of either of the three using positive lookahead first, followed by the sequence for the order itself.