Search code examples
regexsetpermutation

Regex to check non-repetition of a set of characters


Suppose I have the set of characters [ABC]. I'm looking for a regex that would match any permutation of the superset except the empty set, i.e.

ABC ACB BAC BCA CAB CBA
AB BC AC CB CA BA
A B C

The regex should (obviously) not match the empty string.

p.s. An alternative way to express the same objective is "match any non-empty string containing each character in the set at most once".

update: The set [ABC] is just an example, for the real set may also be bigger. With this question I was hoping to find a "general" solution rather than a particular one for [ABC].


Solution

  • Thanks to your answers (especially anubhava's and codaddict's) I was able to find this solution, that I think is pretty elegant because it allows to type the set only once:

    \b(([ABC])(?!.*\2))+\b
    

    the \b are needed to match full words; omitting them will also find subwords respecting the required property. To match a full string, you'd obviously do:

    ^(([ABC])(?!.*\2))+$