Regex to check non-repetition of a set of characters

前端 未结 8 928
无人共我
无人共我 2020-12-19 12:47

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.



        
相关标签:
8条回答
  • 2020-12-19 13:29

    This is not something that regular expressions are good at. You might just want to create a list of permutations instead, and then produce all unique substrings.

    something like:

    def matches(s, characters):
        if len(s) != len(set(s)):
            return False # not unique sequence of characters
        return set(s).issubsetof(set(characters))
    
    0 讨论(0)
  • 2020-12-19 13:29

    OK, I must say that I've thought about your question a lot and - since you seem to be wanting something really universal and customiseable (to support as many elements as possible, etc) - this is what I think would make the most optimal solution.

    What you want, from a math perspective, is to identify all permutations of a set of elements without repetition.


    Step 1 :

    Find all permutations of the set, with repetition (and store them let's say in an array)

    [ABC]([ABC]{1,2})?
    

    Sidenote : let's say you have a set with n elements, all you have to do is :

    [elements]([elements]{1,n-1})?


    Step 2 :

    Filter all permutations with duplicate elements

    Example code in PHP :

    <?php
    
        function strToArray($str)
        {
            $i = 0;
    
            while (isset($str[$i]))
            {
                $result[$i] = $str[$i];
                $i++;
            }
    
            return $result;
        }
    
        function noDuplicates($str)
        {
            if (array_unique(strToArray($str))==strToArray($str)) return true;
            else return false;
        }
    
        $AAA = "AAA";
        $ABC = "ABC";
    
        if (noDuplicates($AAA)) echo "$AAA : ok"; else echo "$AAA : not ok\n";
        if (noDuplicates($ABC)) echo "$ABC : ok"; else echo "$ABC : not ok\n";
    
    ?>
    

    Output :

    AAA : not ok
    ABC : ok
    
    0 讨论(0)
提交回复
热议问题